heraspec 0.1.13 → 0.1.14

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.
Files changed (129) hide show
  1. package/LICENSE +22 -22
  2. package/README.md +188 -119
  3. package/bin/heraspec.js +4800 -1126
  4. package/bin/heraspec.js.map +4 -4
  5. package/dist/core/templates/skills/CHANGELOG.md +117 -117
  6. package/dist/core/templates/skills/README-template.md +58 -58
  7. package/dist/core/templates/skills/README.md +38 -38
  8. package/dist/core/templates/skills/content-optimization-skill.md +104 -104
  9. package/dist/core/templates/skills/data/design-systems.csv +54 -0
  10. package/dist/core/templates/skills/data/pages-proposed.csv +21 -21
  11. package/dist/core/templates/skills/data/pages.csv +9 -9
  12. package/dist/core/templates/skills/data/typography.csv +57 -57
  13. package/dist/core/templates/skills/deploy-documentation-skill.md +408 -0
  14. package/dist/core/templates/skills/design-system-skill.md +176 -0
  15. package/dist/core/templates/skills/documents/templates/documentation-landing-page.html +63 -63
  16. package/dist/core/templates/skills/documents/templates/documentation.html +49 -49
  17. package/dist/core/templates/skills/documents/templates/landing-script.js +38 -38
  18. package/dist/core/templates/skills/documents/templates/landing-style.css +158 -158
  19. package/dist/core/templates/skills/documents/templates/script.js +56 -56
  20. package/dist/core/templates/skills/documents/templates/style.css +155 -155
  21. package/dist/core/templates/skills/documents/templates/technical-doc-template.md +16 -16
  22. package/dist/core/templates/skills/documents/templates/user-guide-template.md +16 -16
  23. package/dist/core/templates/skills/documents-skill.md +104 -104
  24. package/dist/core/templates/skills/e2e-test-skill.md +119 -119
  25. package/dist/core/templates/skills/git-embed-skill.md +57 -0
  26. package/dist/core/templates/skills/integration-test-skill.md +118 -118
  27. package/dist/core/templates/skills/knowledge/README.md +63 -0
  28. package/dist/core/templates/skills/knowledge/design-systems/airbnb/DESIGN.md +246 -0
  29. package/dist/core/templates/skills/knowledge/design-systems/airtable/DESIGN.md +89 -0
  30. package/dist/core/templates/skills/knowledge/design-systems/apple/DESIGN.md +313 -0
  31. package/dist/core/templates/skills/knowledge/design-systems/bmw/DESIGN.md +180 -0
  32. package/dist/core/templates/skills/knowledge/design-systems/cal/DESIGN.md +259 -0
  33. package/dist/core/templates/skills/knowledge/design-systems/claude/DESIGN.md +312 -0
  34. package/dist/core/templates/skills/knowledge/design-systems/clay/DESIGN.md +304 -0
  35. package/dist/core/templates/skills/knowledge/design-systems/clickhouse/DESIGN.md +281 -0
  36. package/dist/core/templates/skills/knowledge/design-systems/cohere/DESIGN.md +266 -0
  37. package/dist/core/templates/skills/knowledge/design-systems/coinbase/DESIGN.md +129 -0
  38. package/dist/core/templates/skills/knowledge/design-systems/composio/DESIGN.md +307 -0
  39. package/dist/core/templates/skills/knowledge/design-systems/cursor/DESIGN.md +309 -0
  40. package/dist/core/templates/skills/knowledge/design-systems/elevenlabs/DESIGN.md +265 -0
  41. package/dist/core/templates/skills/knowledge/design-systems/expo/DESIGN.md +281 -0
  42. package/dist/core/templates/skills/knowledge/design-systems/figma/DESIGN.md +220 -0
  43. package/dist/core/templates/skills/knowledge/design-systems/framer/DESIGN.md +246 -0
  44. package/dist/core/templates/skills/knowledge/design-systems/hashicorp/DESIGN.md +278 -0
  45. package/dist/core/templates/skills/knowledge/design-systems/ibm/DESIGN.md +332 -0
  46. package/dist/core/templates/skills/knowledge/design-systems/index.json +72 -0
  47. package/dist/core/templates/skills/knowledge/design-systems/intercom/DESIGN.md +146 -0
  48. package/dist/core/templates/skills/knowledge/design-systems/kraken/DESIGN.md +125 -0
  49. package/dist/core/templates/skills/knowledge/design-systems/linear.app/DESIGN.md +367 -0
  50. package/dist/core/templates/skills/knowledge/design-systems/lovable/DESIGN.md +298 -0
  51. package/dist/core/templates/skills/knowledge/design-systems/minimax/DESIGN.md +257 -0
  52. package/dist/core/templates/skills/knowledge/design-systems/mintlify/DESIGN.md +326 -0
  53. package/dist/core/templates/skills/knowledge/design-systems/miro/DESIGN.md +108 -0
  54. package/dist/core/templates/skills/knowledge/design-systems/mistral.ai/DESIGN.md +261 -0
  55. package/dist/core/templates/skills/knowledge/design-systems/mongodb/DESIGN.md +266 -0
  56. package/dist/core/templates/skills/knowledge/design-systems/notion/DESIGN.md +309 -0
  57. package/dist/core/templates/skills/knowledge/design-systems/nvidia/DESIGN.md +293 -0
  58. package/dist/core/templates/skills/knowledge/design-systems/ollama/DESIGN.md +267 -0
  59. package/dist/core/templates/skills/knowledge/design-systems/opencode.ai/DESIGN.md +281 -0
  60. package/dist/core/templates/skills/knowledge/design-systems/pinterest/DESIGN.md +230 -0
  61. package/dist/core/templates/skills/knowledge/design-systems/posthog/DESIGN.md +256 -0
  62. package/dist/core/templates/skills/knowledge/design-systems/raycast/DESIGN.md +268 -0
  63. package/dist/core/templates/skills/knowledge/design-systems/replicate/DESIGN.md +261 -0
  64. package/dist/core/templates/skills/knowledge/design-systems/resend/DESIGN.md +303 -0
  65. package/dist/core/templates/skills/knowledge/design-systems/revolut/DESIGN.md +185 -0
  66. package/dist/core/templates/skills/knowledge/design-systems/runwayml/DESIGN.md +244 -0
  67. package/dist/core/templates/skills/knowledge/design-systems/sanity/DESIGN.md +357 -0
  68. package/dist/core/templates/skills/knowledge/design-systems/sentry/DESIGN.md +262 -0
  69. package/dist/core/templates/skills/knowledge/design-systems/spacex/DESIGN.md +194 -0
  70. package/dist/core/templates/skills/knowledge/design-systems/spotify/DESIGN.md +246 -0
  71. package/dist/core/templates/skills/knowledge/design-systems/stripe/DESIGN.md +322 -0
  72. package/dist/core/templates/skills/knowledge/design-systems/supabase/DESIGN.md +255 -0
  73. package/dist/core/templates/skills/knowledge/design-systems/superhuman/DESIGN.md +252 -0
  74. package/dist/core/templates/skills/knowledge/design-systems/together.ai/DESIGN.md +263 -0
  75. package/dist/core/templates/skills/knowledge/design-systems/uber/DESIGN.md +295 -0
  76. package/dist/core/templates/skills/knowledge/design-systems/vercel/DESIGN.md +310 -0
  77. package/dist/core/templates/skills/knowledge/design-systems/voltagent/DESIGN.md +323 -0
  78. package/dist/core/templates/skills/knowledge/design-systems/warp/DESIGN.md +253 -0
  79. package/dist/core/templates/skills/knowledge/design-systems/webflow/DESIGN.md +92 -0
  80. package/dist/core/templates/skills/knowledge/design-systems/wise/DESIGN.md +173 -0
  81. package/dist/core/templates/skills/knowledge/design-systems/x.ai/DESIGN.md +257 -0
  82. package/dist/core/templates/skills/knowledge/design-systems/zapier/DESIGN.md +328 -0
  83. package/dist/core/templates/skills/knowledge/frameworks/php/codeigniter/rise-cms/profile.json +27 -0
  84. package/dist/core/templates/skills/knowledge/frameworks/php/codeigniter/rise-cms/structure.md +137 -0
  85. package/dist/core/templates/skills/knowledge/frameworks/php/laravel/botble/profile.json +39 -0
  86. package/dist/core/templates/skills/knowledge/frameworks/php/laravel/botble/structure.md +208 -0
  87. package/dist/core/templates/skills/knowledge/frameworks/php/wordpress/core/profile.json +51 -0
  88. package/dist/core/templates/skills/knowledge/frameworks/php/wordpress/core/structure.md +369 -0
  89. package/dist/core/templates/skills/knowledge/index.json +65 -0
  90. package/dist/core/templates/skills/module-codebase-skill.md +110 -110
  91. package/dist/core/templates/skills/plugin-directory-skill.md +396 -396
  92. package/dist/core/templates/skills/project-memory-skill.md +222 -0
  93. package/dist/core/templates/skills/project-memory-skill.vi.md +223 -0
  94. package/dist/core/templates/skills/scripts/CODE_EXPLANATION.md +394 -394
  95. package/dist/core/templates/skills/scripts/SEARCH_ALGORITHMS_COMPARISON.md +421 -421
  96. package/dist/core/templates/skills/scripts/SEARCH_MODES_GUIDE.md +238 -238
  97. package/dist/core/templates/skills/scripts/__pycache__/core.cpython-311.pyc +0 -0
  98. package/dist/core/templates/skills/scripts/core.py +391 -385
  99. package/dist/core/templates/skills/scripts/search.py +1 -1
  100. package/dist/core/templates/skills/smart-explore-skill.md +141 -0
  101. package/dist/core/templates/skills/sourcecode-analyzer-skill.md +210 -0
  102. package/dist/core/templates/skills/sourcecode-analyzer-skill.vi.md +210 -0
  103. package/dist/core/templates/skills/suggestion-skill.md +118 -118
  104. package/dist/core/templates/skills/templates/accessibility-checklist.md +40 -40
  105. package/dist/core/templates/skills/templates/example-prompt-full-theme.md +333 -333
  106. package/dist/core/templates/skills/templates/page-types-guide.md +338 -338
  107. package/dist/core/templates/skills/templates/pages-proposed-summary.md +273 -273
  108. package/dist/core/templates/skills/templates/pre-delivery-checklist.md +42 -42
  109. package/dist/core/templates/skills/templates/prompt-template-full-theme.md +313 -313
  110. package/dist/core/templates/skills/templates/responsive-design.md +40 -40
  111. package/dist/core/templates/skills/ui-ux-skill.md +595 -584
  112. package/dist/core/templates/skills/unit-test-skill.md +111 -111
  113. package/dist/core/templates/skills/ux-element/templates/Controller.php +50 -50
  114. package/dist/core/templates/skills/ux-element/templates/Shortcode.php +23 -23
  115. package/dist/core/templates/skills/ux-element/templates/Template.html +20 -20
  116. package/dist/core/templates/skills/ux-element/templates/Thumbnail.svg +8 -8
  117. package/dist/core/templates/skills/ux-element/templates/View.php +21 -21
  118. package/dist/core/templates/skills/ux-element-skill.md +83 -83
  119. package/dist/core/templates/skills/wordpress-plugin-check-skill.md +151 -151
  120. package/dist/core/templates/skills/wordpress-plugin-standard/templates/admin-dashboard.php +47 -47
  121. package/dist/core/templates/skills/wordpress-plugin-standard/templates/admin-settings.php +60 -60
  122. package/dist/core/templates/skills/wordpress-plugin-standard/templates/assets/admin-css.css +22 -22
  123. package/dist/core/templates/skills/wordpress-plugin-standard/templates/assets/admin-js.js +15 -15
  124. package/dist/core/templates/skills/wordpress-plugin-standard/templates/plugin-main.php +169 -169
  125. package/dist/core/templates/skills/wordpress-plugin-standard/templates/readme.txt +41 -41
  126. package/dist/core/templates/skills/wordpress-plugin-standard/templates/uninstall.php +21 -21
  127. package/dist/core/templates/skills/wordpress-plugin-standard-skill.md +100 -100
  128. package/dist/index.js +4068 -278
  129. package/package.json +75 -72
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/cli/index.ts", "../src/core/init.ts", "../src/utils/file-system.ts", "../src/core/templates/index.ts", "../src/core/config.ts", "../src/core/list.ts", "../src/core/archive.ts", "../src/core/parsers/markdown-parser.ts", "../src/core/restore.ts", "../src/commands/show.ts", "../src/utils/task-parser.ts", "../src/core/skills/skill-parser.ts", "../src/core/skills/skill-manager.ts", "../src/commands/validate.ts", "../src/core/validation/validator.ts", "../src/core/schemas/base.schema.ts", "../src/core/schemas/spec.schema.ts", "../src/core/schemas/change.schema.ts", "../src/commands/skill.ts", "../src/core/templates/skills-template-map.ts", "../src/commands/helper.ts", "../src/commands/make-docs.ts", "../src/commands/make-test.ts", "../src/commands/make-code.ts", "../src/commands/suggest.ts"],
4
- "sourcesContent": ["/**\n * HeraSpec CLI Entry Point\n */\nimport { Command } from 'commander';\nimport { createRequire } from 'module';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { InitCommand } from '../core/init.js';\nimport { ListCommand } from '../core/list.js';\nimport { ArchiveCommand } from '../core/archive.js';\nimport { RestoreCommand } from '../core/restore.js';\nimport { ShowCommand } from '../commands/show.js';\nimport { ValidateCommand } from '../commands/validate.js';\nimport { SkillCommand } from '../commands/skill.js';\nimport { HelperCommand } from '../commands/helper.js';\nimport { MakeDocsCommand } from '../commands/make-docs.js';\nimport { MakeTestCommand } from '../commands/make-test.js';\nimport { MakeCodeCommand } from '../commands/make-code.js';\nimport { SuggestCommand } from '../commands/suggest.js';\n\nconst require = createRequire(import.meta.url);\n\n// Get package.json path relative to the built file location\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst packageJsonPath = join(__dirname, '..', 'package.json');\nconst { version } = require(packageJsonPath);\n\nconst program = new Command();\n\nprogram\n .name('heraspec')\n .description('Universal spec-first development framework + CLI')\n .version(version);\n\nprogram\n .command('init [path]')\n .description('Initialize HeraSpec in your project')\n .action(async (targetPath = '.') => {\n try {\n const initCommand = new InitCommand();\n await initCommand.execute(targetPath);\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\nprogram\n .command('list')\n .description('List items (changes by default). Use --specs to list specs.')\n .option('--specs', 'List specs instead of changes')\n .option('--changes', 'List changes explicitly (default)')\n .action(async (options?: { specs?: boolean; changes?: boolean }) => {\n try {\n const listCommand = new ListCommand();\n const mode: 'changes' | 'specs' = options?.specs ? 'specs' : 'changes';\n await listCommand.execute('.', mode);\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\nprogram\n .command('show [item-name]')\n .description('Show a change or spec')\n .action(async (itemName?: string) => {\n try {\n const showCommand = new ShowCommand();\n await showCommand.execute(itemName);\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\nprogram\n .command('validate [item-name]')\n .description('Validate a change or spec')\n .option('--strict', 'Enable strict validation mode')\n .action(async (itemName?: string, options?: { strict?: boolean }) => {\n try {\n const validateCommand = new ValidateCommand();\n await validateCommand.execute(itemName, options);\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\nprogram\n .command('archive [change-name]')\n .description('Archive a completed change and update main specs')\n .option('-y, --yes', 'Skip confirmation prompts')\n .action(async (changeName?: string, options?: { yes?: boolean }) => {\n try {\n const archiveCommand = new ArchiveCommand();\n await archiveCommand.execute(changeName, options);\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\nprogram\n .command('restore [archive-name]')\n .description('Restore an archived change back to active changes')\n .option('-y, --yes', 'Skip confirmation prompts')\n .action(async (archiveName?: string, options?: { yes?: boolean }) => {\n try {\n const restoreCommand = new RestoreCommand();\n await restoreCommand.execute(archiveName, options);\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\nprogram\n .command('view')\n .description('Display an interactive dashboard of specs and changes')\n .action(async () => {\n try {\n const listCommand = new ListCommand();\n console.log('\\n\uD83D\uDCCA HeraSpec Dashboard\\n');\n console.log('\u2550'.repeat(60));\n await listCommand.execute('.', 'changes');\n await listCommand.execute('.', 'specs');\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\nprogram\n .command('skills')\n .description('List all available skills (shortcut for skill list)')\n .action(async () => {\n try {\n const skillCommand = new SkillCommand();\n await skillCommand.list('.');\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\nprogram\n .command('helper')\n .description('Show usage guide, example prompts, and workflow instructions')\n .action(async () => {\n try {\n const helperCommand = new HelperCommand();\n await helperCommand.execute();\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\n// Make commands\nconst makeCmd = program\n .command('make')\n .description('Generate project artifacts');\n\nmakeCmd\n .command('docs')\n .description('Generate project documentation from specs')\n .option('--agent <agent>', 'Specify AI agent for documentation (default: chatgpt)', 'chatgpt')\n .action(async (options?: { agent?: string }) => {\n try {\n const makeDocsCommand = new MakeDocsCommand();\n await makeDocsCommand.execute('.', options?.agent || 'chatgpt');\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\nmakeCmd\n .command('test')\n .description('Generate test cases from specs')\n .option('--type <type>', 'Test type: unit, integration, e2e (default: unit)', 'unit')\n .action(async (options?: { type?: string }) => {\n try {\n const makeTestCommand = new MakeTestCommand();\n await makeTestCommand.execute('.', options?.type || 'unit');\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\nmakeCmd\n .command('code')\n .description('Generate code skeletons from specs')\n .argument('[spec-name]', 'Specific spec to generate code for (optional)')\n .action(async (specName?: string) => {\n try {\n const makeCodeCommand = new MakeCodeCommand();\n await makeCodeCommand.execute('.', specName);\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\nprogram\n .command('suggest')\n .description('Analyze project and suggest new features')\n .action(async () => {\n try {\n const suggestCommand = new SuggestCommand();\n await suggestCommand.execute('.');\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\n// Skill commands\nconst skillCmd = program\n .command('skill')\n .description('Manage and view skills');\n\nskillCmd\n .command('list')\n .description('List all available skills')\n .action(async () => {\n try {\n const skillCommand = new SkillCommand();\n await skillCommand.list('.');\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\nskillCmd\n .command('show <skill-name>')\n .description('Show detailed information about a skill')\n .option('--project-type <type>', 'Specify project type for project-specific skills')\n .action(async (skillName: string, options?: { projectType?: string }) => {\n try {\n const skillCommand = new SkillCommand();\n await skillCommand.show(skillName, options?.projectType, '.');\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\nskillCmd\n .command('repair')\n .description('Repair skills structure to match HeraSpec standards')\n .action(async () => {\n try {\n const skillCommand = new SkillCommand();\n await skillCommand.repair('.');\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\nskillCmd\n .command('add <skill-name>')\n .description('Add a default skill to the project from HeraSpec templates')\n .option('--project-type <type>', 'Specify project type for project-specific skills')\n .action(async (skillName: string, options?: { projectType?: string }) => {\n try {\n const skillCommand = new SkillCommand();\n await skillCommand.add(skillName, options?.projectType, '.');\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\nskillCmd\n .command('update <skill-name>')\n .description('Update an existing skill with the latest from HeraSpec templates')\n .option('--project-type <type>', 'Specify project type for project-specific skills')\n .action(async (skillName: string, options?: { projectType?: string }) => {\n try {\n const skillCommand = new SkillCommand();\n await skillCommand.update(skillName, options?.projectType, '.');\n } catch (error) {\n console.error(`Error: ${(error as Error).message}`);\n process.exit(1);\n }\n });\n\nprogram.parse();\n\n", "/**\n * HeraSpec Init Command\n * Initializes HeraSpec in a project\n */\nimport ora from 'ora';\nimport chalk from 'chalk';\nimport path from 'path';\nimport { FileSystemUtils } from '../utils/file-system.js';\nimport { TemplateManager } from './templates/index.js';\nimport {\n HERASPEC_DIR_NAME,\n SPECS_DIR_NAME,\n CHANGES_DIR_NAME,\n ARCHIVES_DIR_NAME,\n SKILLS_DIR_NAME,\n HERASPEC_MARKERS,\n} from './config.js';\n\nexport class InitCommand {\n async execute(targetPath: string = '.'): Promise<void> {\n const resolvedPath = path.resolve(targetPath);\n const heraspecPath = path.join(resolvedPath, HERASPEC_DIR_NAME);\n\n // Check if already initialized\n const alreadyInitialized = await FileSystemUtils.fileExists(\n path.join(heraspecPath, HERASPEC_MARKERS.PROJECT_MD)\n );\n\n const spinner = ora({\n text: alreadyInitialized ? 'Updating HeraSpec...' : 'Initializing HeraSpec...',\n color: 'blue',\n }).start();\n\n try {\n // Create directory structure\n await FileSystemUtils.createDirectory(heraspecPath);\n await FileSystemUtils.createDirectory(path.join(heraspecPath, SPECS_DIR_NAME));\n await FileSystemUtils.createDirectory(path.join(heraspecPath, CHANGES_DIR_NAME));\n await FileSystemUtils.createDirectory(path.join(heraspecPath, ARCHIVES_DIR_NAME));\n await FileSystemUtils.createDirectory(path.join(heraspecPath, SKILLS_DIR_NAME));\n\n // Create skills README\n const skillsReadmePath = path.join(heraspecPath, SKILLS_DIR_NAME, 'README.md');\n if (!(await FileSystemUtils.fileExists(skillsReadmePath))) {\n const skillsReadme = await this.getSkillsReadmeTemplate();\n await FileSystemUtils.writeFile(skillsReadmePath, skillsReadme);\n }\n\n // Create UI/UX skill quick reference guide\n const uiuxGuidePath = path.join(heraspecPath, SKILLS_DIR_NAME, 'UI_UX_SKILL_QUICK_REFERENCE.md');\n if (!(await FileSystemUtils.fileExists(uiuxGuidePath))) {\n const uiuxGuide = await this.getUIUXQuickReference();\n await FileSystemUtils.writeFile(uiuxGuidePath, uiuxGuide);\n }\n\n // Create template files\n await this.createTemplateFiles(heraspecPath, alreadyInitialized);\n\n // Migration: Check for AGENTS.md and rename it to AGENTS.heraspec.md\n const legacyAgentsPath = path.join(resolvedPath, 'AGENTS.md');\n const newAgentsPath = path.join(resolvedPath, HERASPEC_MARKERS.AGENTS_MD);\n \n if (await FileSystemUtils.fileExists(legacyAgentsPath) && !(await FileSystemUtils.fileExists(newAgentsPath))) {\n await FileSystemUtils.moveFile(legacyAgentsPath, newAgentsPath);\n }\n\n // Create or update root AGENTS.md (merge Skills section if exists)\n await this.updateAgentsFile(newAgentsPath, alreadyInitialized);\n\n // Update related markdown files (README.md, etc.)\n await this.updateRelatedMarkdownFiles(resolvedPath);\n\n spinner.succeed(\n chalk.green(\n alreadyInitialized\n ? 'HeraSpec updated successfully'\n : 'HeraSpec initialized successfully'\n )\n );\n\n console.log();\n console.log(chalk.cyan('Next steps:'));\n console.log(\n chalk.gray('1. Review and update heraspec/project.md with your project details')\n );\n console.log(\n chalk.gray('2. Create your first change: \"Create a HeraSpec change to...\"')\n );\n console.log(\n chalk.gray('3. List changes: heraspec list')\n );\n } catch (error) {\n spinner.fail(chalk.red(`Error: ${(error as Error).message}`));\n throw error;\n }\n }\n\n private async createTemplateFiles(\n heraspecPath: string,\n skipExisting: boolean\n ): Promise<void> {\n const projectMdPath = path.join(heraspecPath, HERASPEC_MARKERS.PROJECT_MD);\n const configYamlPath = path.join(heraspecPath, HERASPEC_MARKERS.CONFIG_YAML);\n\n // Create project.md\n if (!(await FileSystemUtils.fileExists(projectMdPath)) || !skipExisting) {\n await FileSystemUtils.writeFile(\n projectMdPath,\n TemplateManager.getProjectTemplate()\n );\n }\n\n // Create config.yaml\n if (!(await FileSystemUtils.fileExists(configYamlPath)) || !skipExisting) {\n await FileSystemUtils.writeFile(\n configYamlPath,\n TemplateManager.getConfigTemplate()\n );\n }\n }\n\n private async updateAgentsFile(agentsPath: string, alreadyInitialized: boolean): Promise<void> {\n const skillsSectionMarker = '## Skills System';\n\n if (!alreadyInitialized) {\n // New project: create full template\n await FileSystemUtils.writeFile(\n agentsPath,\n TemplateManager.getAgentsTemplate()\n );\n return;\n }\n\n // Existing project: merge or overwrite Skills section to ensure latest rules are applied\n let existingContent = '';\n if (await FileSystemUtils.fileExists(agentsPath)) {\n existingContent = await FileSystemUtils.readFile(agentsPath);\n } else {\n // Root AGENTS.md missing but project initialized? Create it.\n await FileSystemUtils.writeFile(\n agentsPath,\n TemplateManager.getAgentsTemplate()\n );\n return;\n }\n\n // Get the latest Skills section template\n const latestSkillsSection = await this.getSkillsSection();\n \n // Guarantee Universal Safety Rules are up to date\n const safetyMarker = '## Universal Safety Rules';\n const fullTemplate = TemplateManager.getAgentsTemplate();\n const safetyEndIndex = fullTemplate.indexOf('## Core Workflow');\n const safetySection = fullTemplate.substring(fullTemplate.indexOf(safetyMarker), safetyEndIndex).trim();\n\n if (existingContent.includes(safetyMarker)) {\n existingContent = this.replaceSafetyRules(existingContent, safetySection);\n } else {\n // Insert at the beginning or after header\n if (existingContent.startsWith('# ')) {\n const firstLineEnd = existingContent.indexOf('\\n') + 1;\n existingContent = existingContent.substring(0, firstLineEnd) + '\\n' + safetySection + '\\n\\n' + existingContent.substring(firstLineEnd);\n } else {\n existingContent = safetySection + '\\n\\n' + existingContent;\n }\n }\n\n // Update Skills section\n let updatedContent = existingContent;\n if (existingContent.includes(skillsSectionMarker) || existingContent.includes('## Skills system')) {\n updatedContent = this.replaceSkillsSection(existingContent, latestSkillsSection);\n } else {\n updatedContent = this.appendSkillsSection(existingContent, latestSkillsSection);\n }\n \n if (updatedContent !== existingContent) {\n await FileSystemUtils.writeFile(agentsPath, updatedContent);\n }\n }\n\n private replaceSkillsSection(existingContent: string, newSkillsSection: string): string {\n const startMarkers = ['## Skills System', '## Skills system', '### Skills System', '### Skills system'];\n \n let startIndex = -1;\n let foundMarker = '';\n \n for (const marker of startMarkers) {\n startIndex = existingContent.indexOf(marker);\n if (startIndex !== -1) {\n foundMarker = marker;\n break;\n }\n }\n\n if (startIndex === -1) {\n return this.appendSkillsSection(existingContent, newSkillsSection);\n }\n\n // Find the end of Skills section (before next ## section or end of file)\n let endIndex = existingContent.indexOf('\\n## ', startIndex + foundMarker.length);\n if (endIndex === -1) {\n endIndex = existingContent.indexOf('\\n### ', startIndex + foundMarker.length);\n }\n \n if (endIndex === -1) {\n endIndex = existingContent.length;\n }\n\n // Replace the section\n const before = existingContent.substring(0, startIndex).trimEnd();\n const after = existingContent.substring(endIndex);\n return before + '\\n\\n' + newSkillsSection + (after.trimStart().startsWith('\\n') ? '' : '\\n\\n') + after;\n }\n\n private replaceSafetyRules(existingContent: string, newSafetySection: string): string {\n const marker = '## Universal Safety Rules';\n const startIndex = existingContent.indexOf(marker);\n \n if (startIndex === -1) return existingContent;\n\n // Find end of section (next ## header)\n let endIndex = existingContent.indexOf('\\n## ', startIndex + marker.length);\n if (endIndex === -1) {\n endIndex = existingContent.length;\n }\n\n const before = existingContent.substring(0, startIndex).trimEnd();\n const after = existingContent.substring(endIndex);\n \n return before + '\\n\\n' + newSafetySection + (after.trimStart().startsWith('\\n') ? '' : '\\n\\n') + after;\n }\n\n private appendSkillsSection(existingContent: string, skillsSection: string): string {\n // Try to insert before \"## Rules\" section\n const rulesMarker = '\\n## Rules\\n';\n const rulesIndex = existingContent.indexOf(rulesMarker);\n \n if (rulesIndex !== -1) {\n const before = existingContent.substring(0, rulesIndex).trimEnd();\n const after = existingContent.substring(rulesIndex);\n return before + '\\n\\n' + skillsSection + '\\n\\n' + after;\n }\n\n // If no Rules section, try before any \"## Rules\" (without newline)\n const rulesMarker2 = '## Rules';\n const rulesIndex2 = existingContent.indexOf(rulesMarker2);\n if (rulesIndex2 !== -1 && rulesIndex2 > 0) {\n const before = existingContent.substring(0, rulesIndex2).trimEnd();\n const after = existingContent.substring(rulesIndex2);\n return before + '\\n\\n' + skillsSection + '\\n\\n' + after;\n }\n\n // If no Rules section, append at the end\n return existingContent.trimEnd() + '\\n\\n' + skillsSection;\n }\n\n\n private async getSkillsSection(): Promise<string> {\n return TemplateManager.getSkillsSection();\n }\n\n private async getSkillsReadmeTemplate(): Promise<string> {\n return `# Skills Directory\n\nThis directory contains reusable skills for HeraSpec projects.\n\n## What Are Skills?\n\nSkills are reusable patterns and workflows that help AI agents implement tasks consistently. Each skill contains:\n\n- **skill.md**: Complete guide on how to use the skill\n- **templates/**: Reusable templates\n- **scripts/**: Automation scripts\n- **examples/**: Good and bad examples\n\n## How Agents Use Skills\n\nWhen a task has a skill tag:\n\\`\\`\\`markdown\n## 1. Feature (projectType: perfex-module, skill: module-codebase)\n- [ ] Task 1.1\n\\`\\`\\`\n\nThe agent will:\n1. Find skill folder: \\`heraspec/skills/perfex-module/module-codebase/\\`\n2. Read \\`skill.md\\` to understand process\n3. Use templates and scripts from skill folder\n4. Follow guidelines in skill.md\n\n## Available Skills\n\nRun \\`heraspec skill list\\` to see all available skills.\n\n## UI/UX Skill - Creating Full Theme Packages\n\nThe **UI/UX skill** is particularly useful for creating complete website themes with multiple pages.\n\n### Quick Start\n\nWhen you need to create a full website package, use prompts like:\n\n\\`\\`\\`\nT\u1EA1o g\u00F3i website \u0111\u1EA7y \u0111\u1EE7 cho [PRODUCT_TYPE] v\u1EDBi style [STYLE_KEYWORDS].\nS\u1EED d\u1EE5ng skill ui-ux v\u1EDBi hybrid mode \u0111\u1EC3 search design intelligence.\nT\u1EA1o c\u00E1c trang: home, about, [other pages].\nStack: [html-tailwind/react/nextjs].\n\u0110\u1EA3m b\u1EA3o responsive, accessible, consistent design system.\n\\`\\`\\`\n\n### Prompt Templates\n\nFor detailed prompt examples and templates, see:\n- **Example Prompts**: \\`heraspec/skills/ui-ux/templates/example-prompt-full-theme.md\\`\n- **Prompt Templates**: \\`heraspec/skills/ui-ux/templates/prompt-template-full-theme.md\\`\n\nThese templates include:\n- Ready-to-use prompts for different website types (E-commerce, SaaS, Service, Blog, Portfolio)\n- Step-by-step instructions\n- Search command examples\n- Best practices\n\n### Search Modes\n\nUI/UX skill supports 3 search modes:\n- **BM25 (default)**: Fast keyword-based search, zero dependencies\n- **Vector**: Semantic search, ~15-20% better results (requires: \\`pip install sentence-transformers scikit-learn\\`)\n- **Hybrid**: Best of both, ~25% better results (requires: \\`pip install sentence-transformers scikit-learn\\`)\n\n**Usage:**\n\\`\\`\\`bash\n# BM25 (default)\npython3 heraspec/skills/ui-ux/scripts/search.py \"minimalism\" --domain style\n\n# Vector (semantic)\npython3 heraspec/skills/ui-ux/scripts/search.py \"elegant dark theme\" --domain style --mode vector\n\n# Hybrid (best)\npython3 heraspec/skills/ui-ux/scripts/search.py \"modern minimal design\" --domain style --mode hybrid\n\\`\\`\\`\n\n### Multi-Page Support\n\nDefault page set includes:\n1. Home\n2. About\n3. Post Details\n4. Category\n5. Pricing\n6. FAQ\n7. Contact\n8. Product Category (e-commerce)\n9. Product Details (e-commerce)\n\nSearch page types:\n\\`\\`\\`bash\npython3 heraspec/skills/ui-ux/scripts/search.py \"home homepage\" --domain pages\npython3 heraspec/skills/ui-ux/scripts/search.py \"pricing plans\" --domain pages\n\\`\\`\\`\n\n### Adding UI/UX Skill to Your Project\n\n1. Copy skill from HeraSpec core:\n \\`\\`\\`bash\n # Copy UI/UX skill\n cp -r /path/to/HeraSpec/src/core/templates/skills/ui-ux-skill.md heraspec/skills/ui-ux/\n cp -r /path/to/HeraSpec/src/core/templates/skills/scripts heraspec/skills/ui-ux/\n cp -r /path/to/HeraSpec/src/core/templates/skills/data heraspec/skills/ui-ux/\n cp -r /path/to/HeraSpec/src/core/templates/skills/templates heraspec/skills/ui-ux/\n \\`\\`\\`\n\n2. Or use \\`heraspec skill add ui-ux\\` (if available)\n\n3. Read \\`heraspec/skills/ui-ux/ui-ux-skill.md\\` for complete documentation\n\n### Flatsome UX Element Skill\n\nUse the **ux-element** skill when developing elements for UX Builder in Flatsome themes.\n\n**Usage:**\n\\`\\`\\`bash\nheraspec skill add ux-element --project-type wordpress\n\\`\\`\\`\n\nRead \\`heraspec/skills/wordpress/ux-element/skill.md\\` for the **Wrapping Rule** and template usage.\n\n## Creating New Skills\n\n1. Create skill folder structure\n2. Write \\`skill.md\\` following the template\n3. Add templates, scripts, examples as needed\n\nSee \\`docs/SKILLS_STRUCTURE_PROPOSAL.md\\` for detailed structure.\n`;\n }\n\n private async getUIUXQuickReference(): Promise<string> {\n return `# UI/UX Skill - Quick Reference Guide\n\nQuick guide for creating prompts to build full theme packages with multiple pages using the ui-ux skill.\n\n## \uD83D\uDCCB Basic Prompt Template\n\n\\`\\`\\`\nCreate a complete website package for [PRODUCT_TYPE] with the following requirements:\n\n**Project Information:**\n- Product type: [SaaS / E-commerce / Service / Portfolio / etc.]\n- Style: [minimal / elegant / modern / bold / etc.]\n- Industry: [Healthcare / Fintech / Beauty / etc.]\n- Stack: [html-tailwind / react / nextjs / etc.]\n- Pages to create: home, about, [add other pages if needed]\n\n**Process:**\n1. Use skill ui-ux to search design intelligence with hybrid mode\n2. Create shared components first (Header, Footer, Button, Card)\n3. Implement pages in order\n4. Ensure consistency in colors, typography, spacing\n5. Verify with pre-delivery checklist\n\n**Quality Requirements:**\n- \u2705 Consistent design system\n- \u2705 Responsive (320px, 768px, 1024px, 1440px)\n- \u2705 Accessible (WCAG AA minimum)\n- \u2705 Performance optimized\n\\`\\`\\`\n\n## \uD83C\uDFAF Specific Prompt Examples\n\n### E-Commerce\n\\`\\`\\`\nCreate a complete website package for an online fashion store.\n\nProduct type: E-commerce Luxury\nStyle: elegant, premium, sophisticated\nStack: Next.js with Tailwind CSS\nPages: home, about, product category, product details, cart, checkout, thank you, faq, contact\n\nUse skill ui-ux with hybrid mode. Focus on conversion optimization.\n\\`\\`\\`\n\n### SaaS\n\\`\\`\\`\nCreate a complete website package for a project management SaaS platform.\n\nProduct type: SaaS (General)\nStyle: modern, clean, professional\nStack: React with Tailwind CSS\nPages: home, about, pricing, features, faq, contact, login, register, dashboard\n\nUse skill ui-ux with hybrid mode. Ensure professional and trustworthy.\n\\`\\`\\`\n\n### Service Business\n\\`\\`\\`\nCreate a complete website package for a healthcare service.\n\nProduct type: Beauty & Wellness Service\nStyle: elegant, minimal, soft, professional\nStack: html-tailwind\nPages: home, about, services, blog listing, post details, category, pricing, faq, contact\n\nUse skill ui-ux with hybrid mode. Focus on trust and credibility.\n\\`\\`\\`\n\n## \uD83D\uDD0D Search Modes\n\n### BM25 (Default)\n\\`\\`\\`bash\npython3 heraspec/skills/ui-ux/scripts/search.py \"minimalism\" --domain style\n\\`\\`\\`\n- \u2705 Fast, zero dependencies\n- \u2705 Best for exact keyword matches\n\n### Vector (Semantic)\n\\`\\`\\`bash\npython3 heraspec/skills/ui-ux/scripts/search.py \"elegant dark theme\" --domain style --mode vector\n\\`\\`\\`\n- \u2705 Understands meaning and synonyms\n- \u2705 ~15-20% better results\n- \u26A0\uFE0F Requires: \\`pip install sentence-transformers scikit-learn\\`\n\n### Hybrid (Best)\n\\`\\`\\`bash\npython3 heraspec/skills/ui-ux/scripts/search.py \"modern minimal design\" --domain style --mode hybrid\n\\`\\`\\`\n- \u2705 Combines BM25 + Vector\n- \u2705 ~25% better results\n- \u26A0\uFE0F Requires: \\`pip install sentence-transformers scikit-learn\\`\n\n## \uD83D\uDCC4 Default Page Set\n\nWhen creating a \"complete website package\", the default set includes 9 pages:\n\n1. **Home** - Main homepage\n2. **About** - Company/story page\n3. **Post Details** - Blog/article detail\n4. **Category** - Blog/category listing\n5. **Pricing** - Pricing plans\n6. **FAQ** - Frequently asked questions\n7. **Contact** - Contact form\n8. **Product Category** - E-commerce category (if applicable)\n9. **Product Details** - E-commerce product detail (if applicable)\n\n## \uD83D\uDD27 Search Page Types\n\n\\`\\`\\`bash\n# Home page\npython3 heraspec/skills/ui-ux/scripts/search.py \"home homepage\" --domain pages\n\n# About page\npython3 heraspec/skills/ui-ux/scripts/search.py \"about company story\" --domain pages\n\n# Pricing page\npython3 heraspec/skills/ui-ux/scripts/search.py \"pricing plans tiers\" --domain pages\n\n# E-commerce pages\npython3 heraspec/skills/ui-ux/scripts/search.py \"product-category shop catalog\" --domain pages\npython3 heraspec/skills/ui-ux/scripts/search.py \"product-detail single-product\" --domain pages\n\\`\\`\\`\n\n## \uD83D\uDCDA Detailed Documentation\n\nAfter copying UI/UX skill to your project, see:\n- \\`heraspec/skills/ui-ux/ui-ux-skill.md\\` - Complete skill documentation\n- \\`heraspec/skills/ui-ux/templates/example-prompt-full-theme.md\\` - Detailed prompt examples\n- \\`heraspec/skills/ui-ux/templates/prompt-template-full-theme.md\\` - Copy-paste templates\n\n## \uD83D\uDCA1 Tips\n\n1. **Always mention \"skill ui-ux\"** - Agent will know to use this skill\n2. **Encourage using hybrid mode** - Best results\n3. **List all pages clearly** - Agent knows exact scope\n4. **Require consistency** - Ensures unified design system\n5. **Mention pre-delivery checklist** - Agent will verify before delivering\n\n## \uD83D\uDE80 Quick Start\n\n1. Copy UI/UX skill to project:\n \\`\\`\\`bash\n cp -r /path/to/HeraSpec/src/core/templates/skills/ui-ux-skill.md heraspec/skills/ui-ux/\n cp -r /path/to/HeraSpec/src/core/templates/skills/scripts heraspec/skills/ui-ux/\n cp -r /path/to/HeraSpec/src/core/templates/skills/data heraspec/skills/ui-ux/\n cp -r /path/to/HeraSpec/src/core/templates/skills/templates heraspec/skills/ui-ux/\n \\`\\`\\`\n\n2. Use prompt template from above\n\n3. Agent will automatically:\n - Search design intelligence with skill ui-ux\n - Create shared components\n - Implement each page\n - Verify with checklist\n`;\n }\n\n /**\n * Update related markdown files in the project (README.md, etc.)\n */\n private async updateRelatedMarkdownFiles(projectPath: string): Promise<void> {\n // Update README.md if exists\n const readmePath = path.join(projectPath, 'README.md');\n if (await FileSystemUtils.fileExists(readmePath)) {\n await this.updateReadmeFile(readmePath);\n }\n }\n\n /**\n * Update README.md with HeraSpec information\n */\n private async updateReadmeFile(readmePath: string): Promise<void> {\n const existingContent = await FileSystemUtils.readFile(readmePath);\n const heraspecSection = this.getHeraSpecReadmeSection();\n\n // Check if HeraSpec section already exists\n const sectionMarkers = [\n '## HeraSpec',\n '## HeraSpec Development',\n '### HeraSpec',\n '### HeraSpec Development',\n '<!-- HeraSpec Section -->',\n ];\n\n let hasHeraSpecSection = false;\n let sectionStartIndex = -1;\n let sectionEndIndex = -1;\n\n for (const marker of sectionMarkers) {\n const index = existingContent.indexOf(marker);\n if (index !== -1) {\n hasHeraSpecSection = true;\n sectionStartIndex = index;\n // Find the end of the section (next ## or end of file)\n sectionEndIndex = existingContent.indexOf('\\n## ', index + marker.length);\n if (sectionEndIndex === -1) {\n sectionEndIndex = existingContent.indexOf('\\n### ', index + marker.length);\n }\n if (sectionEndIndex === -1) {\n sectionEndIndex = existingContent.length;\n }\n break;\n }\n }\n\n if (hasHeraSpecSection && sectionStartIndex !== -1) {\n // Update existing section\n const before = existingContent.substring(0, sectionStartIndex).trimEnd();\n const after = existingContent.substring(sectionEndIndex);\n const updatedContent = before + '\\n\\n' + heraspecSection + (after.trimStart().startsWith('\\n') ? '' : '\\n\\n') + after;\n await FileSystemUtils.writeFile(readmePath, updatedContent);\n } else {\n // Add new section\n // Try to insert before common sections like \"## Development\", \"## Setup\", \"## Contributing\"\n const insertBeforeMarkers = [\n '\\n## Development',\n '\\n## Setup',\n '\\n## Contributing',\n '\\n## Installation',\n '\\n## Getting Started',\n ];\n\n let inserted = false;\n for (const marker of insertBeforeMarkers) {\n const index = existingContent.indexOf(marker);\n if (index !== -1) {\n const before = existingContent.substring(0, index).trimEnd();\n const after = existingContent.substring(index);\n const updatedContent = before + '\\n\\n' + heraspecSection + '\\n\\n' + after;\n await FileSystemUtils.writeFile(readmePath, updatedContent);\n inserted = true;\n break;\n }\n }\n\n if (!inserted) {\n // Append at the end\n const updatedContent = existingContent.trimEnd() + '\\n\\n' + heraspecSection;\n await FileSystemUtils.writeFile(readmePath, updatedContent);\n }\n }\n }\n\n /**\n * Get HeraSpec section content for README.md\n */\n private getHeraSpecReadmeSection(): string {\n return `<!-- HeraSpec Section -->\n## HeraSpec Development\n\nThis project uses [HeraSpec](https://github.com/your-org/heraspec) for spec-driven development.\n\n### Quick Start\n\n\\`\\`\\`bash\n# Initialize HeraSpec (if not already done)\nheraspec init\n\n# List active changes\nheraspec list\n\n# View a change\nheraspec show <change-name>\n\n# Validate changes\nheraspec validate <change-name>\n\\`\\`\\`\n\n### Project Structure\n\n- \\`heraspec/project.md\\` - Project overview and configuration\n- \\`heraspec/specs/\\` - Source of truth specifications\n- \\`heraspec/changes/\\` - Active changes in progress\n- \\`heraspec/skills/\\` - Reusable skills for AI agents\n- \\`AGENTS.heraspec.md\\` - AI agent instructions\n\n### Working with Changes\n\n1. **Create a change**: Ask AI to create a HeraSpec change, or create manually\n2. **Refine specs**: Review and update delta specs in \\`heraspec/specs/<change-name>/\\`\n3. **Implement**: Follow tasks in \\`heraspec/changes/<change-name>/tasks.md\\`\n4. **Archive**: Run \\`heraspec archive <change-name> --yes\\` when complete\n\n### Skills\n\nAdd skills to your project:\n\n\\`\\`\\`bash\n# List available skills\nheraspec skill list\n\n# Add a skill\nheraspec skill add ui-ux\nheraspec skill add unit-test\n\n# View skill details\nheraspec skill show ui-ux\n\\`\\`\\`\n\nFor more information, see the [HeraSpec documentation](https://github.com/your-org/heraspec/docs).\n\n---\n\n*This section is automatically updated by \\`heraspec init\\`. Last updated: ${new Date().toISOString().split('T')[0]}*`;\n }\n}\n\n", "/**\n * File system utilities for HeraSpec\n */\nimport { promises as fs } from 'fs';\nimport path from 'path';\n\nexport class FileSystemUtils {\n static async createDirectory(dirPath: string): Promise<void> {\n await fs.mkdir(dirPath, { recursive: true });\n }\n\n static async fileExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n }\n\n static async readFile(filePath: string): Promise<string> {\n return await fs.readFile(filePath, 'utf-8');\n }\n\n static async writeFile(filePath: string, content: string): Promise<void> {\n await fs.writeFile(filePath, content, 'utf-8');\n }\n\n static async readDirectory(dirPath: string): Promise<string[]> {\n return await fs.readdir(dirPath);\n }\n\n static async stat(filePath: string) {\n return await fs.stat(filePath);\n }\n\n static async copyFile(src: string, dest: string): Promise<void> {\n await fs.copyFile(src, dest);\n }\n\n static async copyDirectory(src: string, dest: string): Promise<void> {\n await fs.mkdir(dest, { recursive: true });\n const entries = await fs.readdir(src, { withFileTypes: true });\n\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n\n if (entry.isDirectory()) {\n await this.copyDirectory(srcPath, destPath);\n } else {\n await fs.copyFile(srcPath, destPath);\n }\n }\n }\n\n static async removeFile(filePath: string): Promise<void> {\n await fs.unlink(filePath);\n }\n\n static async removeDirectory(dirPath: string, recursive = true): Promise<void> {\n // Use fs.rm for Node.js 14.14.0+ (fs.rmdir with recursive is deprecated)\n // Fallback to fs.rmdir for older versions\n if (typeof (fs as any).rm === 'function') {\n await (fs as any).rm(dirPath, { recursive, force: true });\n } else {\n await fs.rmdir(dirPath, { recursive });\n }\n }\n\n static async moveFile(src: string, dest: string): Promise<void> {\n await fs.rename(src, dest);\n }\n\n static joinPath(...segments: string[]): string {\n return path.join(...segments);\n }\n\n static resolvePath(...segments: string[]): string {\n return path.resolve(...segments);\n }\n\n static getDirectoryName(filePath: string): string {\n return path.dirname(filePath);\n }\n\n static getBaseName(filePath: string): string {\n return path.basename(filePath);\n }\n}\n", "/**\n * HeraSpec Templates\n */\n\nexport class TemplateManager {\n static getProjectTemplate(): string {\n return `# HeraSpec Project\n\n## Overview\nDescribe your project here.\n\n## Project Types\n- wordpress-plugin\n- wordpress-theme\n- perfex-module\n- laravel-package\n- node-service\n- generic-webapp\n- backend-api\n- frontend-app\n- multi-stack\n\n## Tech Stack\nList your technologies here (e.g., PHP 8.1, WordPress 6.0, Laravel 10, etc.)\n\n## Conventions\nDefine coding standards, architectural patterns, and conventions to follow.\n`;\n }\n\n static getAgentsTemplate(): string {\n return `# HeraSpec \u2014 AI Agent Instructions\n\nThis document defines the workflow for AI agents working with HeraSpec.\n\n## Universal Safety Rules\n\n- **NO AUTO-COMMIT**: Agent MUST NOT perform \\`git commit\\` or \\`git push\\` autonomously. This task is reserved for the User unless explicitly ordered.\n- **NO AUTO-PUBLISH**: Agent MUST NOT perform \\`npm publish\\` or trigger automated releases/deployments autonomously.\n- **SKILL PREREQUISITE**: If a task maps to a skill (e.g., \"Generate documentation\"), you **MUST** verify the skill folder exists in \\`heraspec/skills/\\`. If missing:\n - **Preferred**: Proactively install it via \\`heraspec skill add <name>\\` (e.g., \\`heraspec skill add documents\\`) if you have terminal access.\n - **Fallback**: If you cannot install it, **STOP** and ask the user to add it. **DO NOT** attempt manual generation without the skill.\n- **USER CONFIRMATION**: For destructive actions or public releases, always request explicit User approval first.\n\n### Restricted Commands (REQUIRE USER CONFIRMATION)\n\nThe following commands are classified by risk level. You **MUST NOT** execute them without explicit user confirmation/approval in the chat, especially if they are outside the source workspace or involve deletion.\n\n#### GROUP 1 \u2013 EXTREMELY DANGEROUS (DATA DESTRUCTION, HARD / IMPOSSIBLE TO RECOVER)\n- \\`rm -rf\\` : Recursive delete + no prompt, can wipe entire system\n- \\`rm -r\\` : Delete directory and all contents\n- \\`rm\\` : Delete file directly, bypassing trash\n- \\`unlink\\` : Delete file at filesystem level, cannot undo\n- \\`shred\\` : Overwrite data multiple times to make it unrecoverable\n- \\`wipe\\` : Permanently wipe data on disk\n- \\`dd\\` : Write/copy raw blocks, easily destroy disk or partition\n- \\`mkfs\\`, \\`mkfs.ext4\\`, \\`mkfs.xfs\\` : Create new filesystem, wiping old data\n- \\`format\\`, \\`Format-Volume\\` : Format drive/volume\n\n#### GROUP 2 \u2013 HIGH DANGER (DELETE DIRECTORY / MULTIPLE FILES)\n- \\`rmdir\\` : Delete directory\n- \\`rd\\`, \\`rmdir /s\\` : Windows delete directory\n- \\`Remove-Item -Recurse\\`, \\`Remove-Item\\` : PowerShell delete\n- \\`del /s\\`, \\`erase /s\\` : CMD batch delete\n\n#### GROUP 3 \u2013 MEDIUM DANGER (DELETE FILE / OVERWRITE)\n- \\`del\\`, \\`erase\\` : Delete file\n- \\`Clear-Content\\` : Clear file content\n- \\`cp --remove-destination\\` : Overwrite destination by deleting first\n\n#### GROUP 4 \u2013 INDIRECT DANGER (DATA LOSS)\n- \\`mv\\` : Move / overwrite file, old data lost\n- \\`rsync --delete\\` : Delete file at destination if not in source\n- \\`install\\` : Overwrite system files\n\n#### GROUP 5 \u2013 DISK / PARTITION MANAGEMENT\n- \\`fdisk\\`, \\`cfdisk\\`, \\`parted\\`, \\`diskpart\\` : Partition management\n- \\`mount\\`, \\`umount\\` : Filesystem mounting\n\n#### GROUP 6 \u2013 LESS DANGEROUS (POTENTIAL CONSEQUENCES)\n- \\`truncate\\` : Cutt off file content\n- \\`chown\\`, \\`chmod\\` : Change ownership/permissions\n- \\`attrib\\` : Change attributes\n\n## Core Workflow\n\n### Step 1 \u2014 Create a Change\n\n**When creating changes, ALWAYS read heraspec/project.md first to understand:**\n- Project types being used\n- Tech stack and conventions\n- Existing architecture patterns\n- Coding standards\n\n**Then scaffold:**\n- \\`heraspec/changes/<slug>/\\` - Create proposal.md, tasks.md, design.md (optional)\n- \\`heraspec/specs/<slug>/\\` - Create delta specs here (NOT inside changes folder)\n\n**If user asks to create changes based on project.md:**\n1. Read \\`heraspec/project.md\\` thoroughly\n2. Identify all features/capabilities mentioned\n3. Create separate changes for each major feature\n4. Ensure each change follows project.md conventions\n5. Use correct project types and skills from project.md\n\n### Step 2 \u2014 Refine Specs\n- Update delta specs in \\`heraspec/specs/<slug>/\\`\n- Never modify source-of-truth specs directly\n\n### Step 3 \u2014 Approval\n- Wait for user: \"Specs approved.\"\n\n### Step 4 \u2014 Implementation\n\n**CRITICAL: When implementing tasks, ALWAYS use Skills system:**\n\n1. **Read task line** to identify skill:\n \\`\\`\\`markdown\n ## 1. Perfex module \u2013 Category Management (projectType: perfex-module, skill: module-codebase)\n - [ ] 1.1 Create module structure\n \\`\\`\\`\n\n2. **Find skill folder**:\n - Project-specific: \\`heraspec/skills/<project-type>/<skill-name>/\\`\n - Cross-cutting: \\`heraspec/skills/<skill-name>/\\`\n\n3. **Read skill.md**:\n - Understand purpose, steps, inputs, outputs\n - Follow tone, rules, and limitations\n - Check available templates and scripts\n\n4. **Use skill resources**:\n - Run scripts from \\`scripts/\\` folder if needed\n - Use templates from \\`templates/\\` folder\n - Reference examples from \\`examples/\\` folder\n\n5. **Implement following skill.md guidance**:\n - Follow step-by-step process\n - Use correct naming conventions\n - Apply code style rules\n - Respect limitations\n\n**Example workflow:**\n- Task: \\`(projectType: perfex-module, skill: module-codebase)\\`\n- Agent reads: \\`heraspec/skills/perfex-module/module-codebase/skill.md\\`\n- Agent follows: Steps, uses templates, runs scripts\n- Agent implements: According to skill.md guidelines\n\n**Special case - UI/UX skill:**\n- Task: \\`(skill: ui-ux)\\`\n- Agent reads: \\`heraspec/skills/ui-ux/skill.md\\`\n- Agent MUST use search scripts before implementing:\n \\`\\`\\`bash\n # Search for design intelligence\n python3 heraspec/skills/ui-ux/scripts/search.py \"<keyword>\" --domain <domain>\n python3 heraspec/skills/ui-ux/scripts/search.py \"<keyword>\" --stack <stack>\n \\`\\`\\`\n- Agent synthesizes search results\n- Agent implements with proper colors, fonts, styles from search results\n- Agent verifies with pre-delivery checklist\n\n**Special case - Flatsome UX Element skill:**\n- Task: \\`(projectType: wordpress, skill: ux-element)\\`\n- Agent reads: \\`heraspec/skills/wordpress/ux-element/skill.md\\`\n- Agent MUST follow the **Wrapping Rule**: Use \\`<span>\\` with \\`id=\"{{:: shortcode.$id }}\"\\`\n- Agent uses templates from \\`heraspec/skills/wordpress/ux-element/templates/\\` (Controller, Shortcode, HTML Template, SVG Thumbnail)\n- Agent ensures real-time preview support in AngularJS template.\n- **Variable Translation**: Variables with underscores in PHP (e.g., \\`bg_color\\`) MUST be accessed via camelCase in AngularJS (e.g., \\`shortcode.options.bgColor\\`).\n\n**Special case - Plugin Check skill:**\n- Task: \\`(projectType: wordpress-plugin, skill: plugin-check)\\`\n- Install: \\`heraspec skill add plugin-check --project-type wordpress-plugin\\`\n- Agent reads: \\`heraspec/skills/wordpress-plugin/plugin-check/skill.md\\`\n- Agent runs WordPress Plugin Check (PCP) tool\n- Agent fixes coding standard issues iteratively until all pass\n\n**Special case - Plugin Directory skill:**\n- Task: \\`(projectType: wordpress-plugin, skill: plugin-directory)\\`\n- Install: \\`heraspec skill add plugin-directory --project-type wordpress-plugin\\`\n- Agent reads: \\`heraspec/skills/wordpress-plugin/plugin-directory/skill.md\\`\n- Agent MUST review plugin against **18 WordPress.org Directory Guidelines**:\n 1. GPL Compatibility\n 2. Developer Responsibility\n 3. Stable Version Availability\n 4. Human Readable Code\n 5. No Trialware\n 6. Software as a Service\n 7. User Tracking Consent\n 8. No External Executable Code\n 9. Legal and Ethical Conduct\n 10. External Links and Credits\n 11. Admin Dashboard Experience\n 12. No Spam in Public Pages\n 13. WordPress Default Libraries\n 14. Commit Frequency\n 15. Version Number Increment\n 16. Complete Plugin Required\n 17. Trademark and Copyright\n 18. Directory Maintenance Rights\n- Agent generates a **Compliance Report** with:\n - \u2705 Passed items\n - \u26A0\uFE0F Items needing review \n - \u274C Violations with file paths and line numbers\n- **CRITICAL**: Agent MUST present full report and **wait for user confirmation** before making changes\n- Reference guideline numbers (e.g., \"Guideline 7: User Tracking Consent\")\n\n\n- Follow tasks.md\n- Mark tasks completed: \\`- [x]\\`\n\n### Step 5 \u2014 Archive\n- Run: \\`heraspec archive <slug> --yes\\`\n- This merges delta specs into source specs\n- Moves change folder to archives\n\n## Spec Format\n\nSpecs must include:\n- \\`## Meta\\` section with project type, domain, stack\n- \\`## Purpose\\`\n- \\`## Requirements\\` with scenarios\n\n## Delta Spec Format\n\nDelta specs use:\n- \\`## ADDED Requirements\\`\n- \\`## MODIFIED Requirements\\`\n- \\`## REMOVED Requirements\\`\n\n## Tasks Format\n\nTasks grouped by project type and skill:\n\\`\\`\\`\n## 1. WordPress plugin \u2013 admin settings page (projectType: wordpress-plugin, skill: admin-settings-page)\n- [ ] Task description\n\\`\\`\\`\n\n## Skills System\n\n**CRITICAL: Mandatory Prerequisite Check**\n\n1. **Stop & Verify**: If you are asked to implement a task requiring a skill (e.g., \"Generate documentation...\", \"Create UI/UX...\", etc.), you MUST first check if the skill folder exists in \\`heraspec/skills/\\`.\n2. **Missing Skill = AUTO-INSTALL OR STOP**: If the skill folder does NOT exist:\n - **Option A (Preferred)**: If you can run commands, execute \\`heraspec skill add <skill-name>\\` immediately.\n - **Option B (Fallback)**: If you cannot run commands, **STOP** and ask the user to run it.\n > \"Tip: Add the 'documents' skill for premium HTML & Landing Page support: \n > heraspec skill add documents\"\n - **DO NOT** create a task plan or attempt manual generation without the skill language.\n3. **Execute After Install**: Only after the skill folder is created (or installed), read the \\`skill.md\\` and proceed with the task.\n\n**Example prompt for Documents skill:**\nIf you need to generate multi-format documentation, use this prompt:\n> \"Generate documentation with skill documents for [project-name]. Include:\n> - Concise overview (documentations/documentation.txt)\n> - Technical Markdown (documentations/documentation.md)\n> - Interactive HTML (documentations/documentation.html)\n> - Premium Documentation Landing Page (documentations/documentation-landing-page.html)\n> - CRITICAL: Save all files in the /documentations directory (create it if missing).\"\n\n**Dynamic Documentation Generation**:\nWhen generating documentation, do NOT simply fill a template. The Agent MUST:\n1. **Create** the \\`/documentations\\` directory if it does not exist.\n2. **Design** a custom layout and content structure suitable for the project type.\n3. **Synchronize** with the \\`ui-ux\\` skill for premium visual design (colors, typography, animations).\n4. **Scan All Specs**: If project-wide, read \\`heraspec/project.md\\` and all files in \\`heraspec/specs/\\` to synthesize the content.\n\n### Skill Discovery & Usage\n\n- List all skills: Check \\`heraspec/skills/\\` directory\n- Project-specific skills: \\`heraspec/skills/<project-type>/\\`\n- Cross-cutting skills: \\`heraspec/skills/<skill-name>/\\` (root level)\n- **Consistency**: Follow the step-by-step process in the skill's \\`skill.md\\`.\n\n### When Change Has Multiple Skills\n\n**Important**: Each task group uses ONE skill. When working on a task group, agent MUST use that skill's skill.md.\n\nExample with multiple skills in one change:\n\\`\\`\\`\n## 1. WordPress module \u2013 Feature (skill: admin-settings-page)\n- [ ] Task 1.1 Create module structure\n- [ ] Task 1.2 Configure registration\n\n## 2. UI/UX \u2013 Admin Interface (skill: ui-ux)\n- [ ] Task 2.1 Design color palette\n- [ ] Task 2.2 Create component styles\n\n## 3. Documents \u2013 User Guide (skill: documents)\n- [ ] Task 3.1 Write technical docs\n\\`\\`\\`\n\n**Key rule**: Switch skill.md when switching task groups!\n`;\n }\n\n static getSkillsSection(): string {\n return `## Skills System\n\n**CRITICAL: Mandatory Prerequisite Check**\n\n1. **Stop & Verify**: If you are asked to implement a task requiring a skill (e.g., \"Generate documentation...\", \"Create UI/UX...\", etc.), you MUST first check if the skill folder exists in \\`heraspec/skills/\\`.\n2. **Missing Skill = AUTO-INSTALL OR STOP**: If the skill folder does NOT exist:\n - **Option A (Preferred)**: If you can run commands, execute \\`heraspec skill add <skill-name>\\` immediately.\n - **Option B (Fallback)**: If you cannot run commands, **STOP** and ask the user to run it.\n > \"Tip: Add the 'documents' skill for premium HTML & Landing Page support: \n > heraspec skill add documents\"\n - **DO NOT** create a task plan or attempt manual generation without the skill language.\n3. **Execute After Install**: Only after the skill folder is created (or installed), read the \\`skill.md\\` and proceed with the task.\n\n**Example prompt for Documents skill:**\nIf you need to generate multi-format documentation, use this prompt:\n> \"Generate documentation with skill documents for [project-name]. Include:\n> - Concise overview (documentations/documentation.txt)\n> - Technical Markdown (documentations/documentation.md)\n> - Interactive HTML (documentations/documentation.html)\n> - Premium Documentation Landing Page (documentations/documentation-landing-page.html)\n> - CRITICAL: Save all files in the /documentations directory (create it if missing).\"\n\n**Dynamic Documentation Generation**:\nWhen generating documentation, do NOT simply fill a template. The Agent MUST:\n1. **Create** the \\`/documentations\\` directory if it does not exist.\n2. **Design** a custom layout and content structure suitable for the project type.\n3. **Synchronize** with the \\`ui-ux\\` skill for premium visual design (colors, typography, animations).\n4. **Scan All Specs**: If project-wide, read \\`heraspec/project.md\\` and all files in \\`heraspec/specs/\\` to synthesize the content.\n\n### Skill Discovery & Usage\n\n- List all skills: Check \\`heraspec/skills/\\` directory\n- Project-specific skills: \\`heraspec/skills/<project-type>/\\`\n- Cross-cutting skills: \\`heraspec/skills/<skill-name>/\\` (root level)\n- **Consistency**: Follow the step-by-step process in the skill's \\`skill.md\\`.\n\n### When Change Has Multiple Skills\n\n**Important**: Each task group uses ONE skill. When working on a task group, agent MUST use that skill's skill.md.\n\nExample with multiple skills in one change:\n\\`\\`\\`\n## 1. WordPress module \u2013 Feature (skill: admin-settings-page)\n- [ ] Task 1.1 Create module structure\n- [ ] Task 1.2 Configure registration\n\n## 2. UI/UX \u2013 Admin Interface (skill: ui-ux)\n- [ ] Task 2.1 Design color palette\n- [ ] Task 2.2 Create component styles\n\n## 3. Documents \u2013 User Guide (skill: documents)\n- [ ] Task 3.1 Write technical docs\n\\`\\`\\`\n\n**Key rule**: Switch skill.md when switching task groups!\n`;\n }\n\n static getConfigTemplate(): string {\n return `projectType: generic-webapp\nprojectName: \"HeraSpec Project\"\ndescription: \"A new project using HeraSpec\"\nskills: []\n`;\n }\n}\n", "/**\n * HeraSpec Core Configuration\n */\n\nexport const HERASPEC_DIR_NAME = 'heraspec';\nexport const SPECS_DIR_NAME = 'specs';\nexport const CHANGES_DIR_NAME = 'changes';\nexport const ARCHIVES_DIR_NAME = 'archives';\nexport const SKILLS_DIR_NAME = 'skills';\n\nexport const PROJECT_TYPES = [\n 'wordpress-plugin',\n 'wordpress-theme',\n 'perfex-module',\n 'laravel-package',\n 'node-service',\n 'generic-webapp',\n 'backend-api',\n 'frontend-app',\n 'multi-stack',\n] as const;\n\nexport type ProjectType = (typeof PROJECT_TYPES)[number];\n\nexport const SKILLS: Record<ProjectType, string[]> = {\n 'wordpress-plugin': [\n 'admin-settings-page',\n 'custom-post-type',\n 'shortcode',\n 'rest-endpoint',\n 'ajax-handler',\n 'activation-hook',\n 'deactivation-hook',\n 'admin-menu-item',\n 'meta-box',\n 'taxonomy',\n 'plugin-check',\n 'plugin-directory',\n ],\n 'wordpress-theme': [\n 'theme-setup',\n 'custom-post-type',\n 'template-part',\n 'widget-area',\n 'customizer-setting',\n 'theme-option',\n ],\n 'perfex-module': [\n 'module-codebase',\n 'module-registration',\n 'permission-group',\n 'admin-menu-item',\n 'login-hook',\n 'database-table',\n 'api-endpoint',\n ],\n 'laravel-package': [\n 'service-provider',\n 'config-file',\n 'artisan-command',\n 'migration',\n 'model',\n 'controller',\n 'middleware',\n 'route',\n ],\n 'node-service': [\n 'express-route',\n 'middleware',\n 'database-model',\n 'service-layer',\n 'api-endpoint',\n 'background-job',\n ],\n 'generic-webapp': [\n 'page',\n 'component',\n 'api-endpoint',\n 'database-table',\n 'authentication',\n 'authorization',\n ],\n 'backend-api': [\n 'endpoint',\n 'middleware',\n 'authentication',\n 'authorization',\n 'database-model',\n 'validation',\n ],\n 'frontend-app': [\n 'page',\n 'component',\n 'route',\n 'store',\n 'service',\n 'hook',\n ],\n 'multi-stack': [\n 'cross-platform-feature',\n 'api-contract',\n 'shared-type',\n 'integration-point',\n ],\n} as const;\n\nexport type Skill = typeof SKILLS[ProjectType][number];\n\nexport interface HeraSpecConfig {\n projectType?: ProjectType | ProjectType[];\n domains?: string[];\n stack?: string[];\n}\n\nexport interface SpecMeta {\n projectType?: ProjectType | ProjectType[];\n domain?: string;\n stack?: string | string[];\n}\n\nexport const HERASPEC_MARKERS = {\n PROJECT_MD: 'project.md',\n AGENTS_MD: 'AGENTS.heraspec.md',\n CONFIG_YAML: 'config.yaml',\n PROPOSAL_MD: 'proposal.md',\n TASKS_MD: 'tasks.md',\n DESIGN_MD: 'design.md',\n} as const;\n\n", "/**\n * HeraSpec List Command\n * Lists changes or specs\n */\nimport path from 'path';\nimport { FileSystemUtils } from '../utils/file-system.js';\nimport { HERASPEC_DIR_NAME, CHANGES_DIR_NAME, SPECS_DIR_NAME, ARCHIVES_DIR_NAME } from './config.js';\n\nexport class ListCommand {\n async execute(\n targetPath: string = '.',\n mode: 'changes' | 'specs' = 'changes'\n ): Promise<void> {\n const heraspecPath = path.join(targetPath, HERASPEC_DIR_NAME);\n\n if (mode === 'changes') {\n await this.listChanges(heraspecPath);\n } else {\n await this.listSpecs(heraspecPath);\n }\n }\n\n private async listChanges(heraspecPath: string): Promise<void> {\n const changesDir = path.join(heraspecPath, CHANGES_DIR_NAME);\n\n try {\n await FileSystemUtils.stat(changesDir);\n } catch {\n console.log('No HeraSpec changes directory found. Run \"heraspec init\" first.');\n return;\n }\n\n const entries = await FileSystemUtils.readDirectory(changesDir);\n const changeDirs: string[] = [];\n\n for (const entry of entries) {\n const entryPath = path.join(changesDir, entry);\n const stats = await FileSystemUtils.stat(entryPath);\n if (stats.isDirectory() && entry !== ARCHIVES_DIR_NAME) {\n changeDirs.push(entry);\n }\n }\n\n if (changeDirs.length === 0) {\n console.log('No active changes found.');\n return;\n }\n\n changeDirs.sort();\n\n console.log('\\nActive changes:');\n console.log('\u2500'.repeat(50));\n for (const change of changeDirs) {\n console.log(` \u2022 ${change}`);\n }\n console.log();\n }\n\n private async listSpecs(heraspecPath: string): Promise<void> {\n const specsDir = path.join(heraspecPath, SPECS_DIR_NAME);\n\n try {\n await FileSystemUtils.stat(specsDir);\n } catch {\n console.log('No HeraSpec specs directory found. Run \"heraspec init\" first.');\n return;\n }\n\n const specs = await this.findSpecFiles(specsDir, '');\n\n if (specs.length === 0) {\n console.log('No specs found.');\n return;\n }\n\n specs.sort();\n\n console.log('\\nSpecs:');\n console.log('\u2500'.repeat(50));\n for (const spec of specs) {\n console.log(` \u2022 ${spec}`);\n }\n console.log();\n }\n\n private async findSpecFiles(dir: string, prefix: string): Promise<string[]> {\n const specs: string[] = [];\n const entries = await FileSystemUtils.readDirectory(dir);\n\n for (const entry of entries) {\n const entryPath = path.join(dir, entry);\n const stats = await FileSystemUtils.stat(entryPath);\n\n if (stats.isDirectory()) {\n const subSpecs = await this.findSpecFiles(\n entryPath,\n prefix ? `${prefix}/${entry}` : entry\n );\n specs.push(...subSpecs);\n } else if (entry === 'spec.md') {\n specs.push(prefix || 'global');\n }\n }\n\n return specs;\n }\n}\n\n", "/**\n * HeraSpec Archive Command\n * Archives a change and merges delta specs into source specs\n */\nimport path from 'path';\nimport ora from 'ora';\nimport chalk from 'chalk';\nimport { FileSystemUtils } from '../utils/file-system.js';\nimport {\n HERASPEC_DIR_NAME,\n CHANGES_DIR_NAME,\n ARCHIVES_DIR_NAME,\n SPECS_DIR_NAME,\n} from './config.js';\nimport { MarkdownParser } from './parsers/markdown-parser.js';\n\nexport class ArchiveCommand {\n async execute(changeName?: string, options?: { yes?: boolean }): Promise<void> {\n if (!changeName) {\n console.error('Error: Please specify a change name');\n console.log('Usage: heraspec archive <change-name> [--yes]');\n process.exitCode = 1;\n return;\n }\n\n const changePath = path.join('.', HERASPEC_DIR_NAME, CHANGES_DIR_NAME, changeName);\n\n if (!(await FileSystemUtils.fileExists(changePath))) {\n console.error(`Error: Change \"${changeName}\" not found`);\n process.exitCode = 1;\n return;\n }\n\n // Confirm if not --yes\n if (!options?.yes) {\n console.log(`\\nThis will archive \"${changeName}\" and merge delta specs into source specs.`);\n console.log('This action cannot be undone.\\n');\n // In a real implementation, you'd prompt here\n // For now, we'll require --yes flag\n console.error('Error: Please use --yes flag to confirm');\n process.exitCode = 1;\n return;\n }\n\n const spinner = ora({\n text: `Archiving change \"${changeName}\"...`,\n color: 'blue',\n }).start();\n\n try {\n // 1. Merge delta specs into source specs\n await this.mergeDeltaSpecs(changePath, changeName);\n\n // 2. Remove specs directory after merge (specs are now in source specs)\n const specsDir = path.join(\n '.',\n HERASPEC_DIR_NAME,\n SPECS_DIR_NAME,\n changeName\n );\n if (await FileSystemUtils.fileExists(specsDir)) {\n await FileSystemUtils.removeDirectory(specsDir, true);\n }\n\n // 3. Create archive directory with date prefix\n const archiveDir = path.join(\n '.',\n HERASPEC_DIR_NAME,\n CHANGES_DIR_NAME,\n ARCHIVES_DIR_NAME\n );\n await FileSystemUtils.createDirectory(archiveDir);\n\n const datePrefix = new Date().toISOString().split('T')[0];\n const archivePath = path.join(archiveDir, `${datePrefix}-${changeName}`);\n\n // 4. Move change to archive\n await FileSystemUtils.createDirectory(archivePath);\n await this.moveChangeToArchive(changePath, archivePath);\n\n // 5. Remove original change directory\n await FileSystemUtils.removeDirectory(changePath, true);\n\n spinner.succeed(chalk.green(`Change \"${changeName}\" archived successfully`));\n } catch (error) {\n spinner.fail(chalk.red(`Error: ${(error as Error).message}`));\n throw error;\n }\n }\n\n private async mergeDeltaSpecs(changePath: string, changeName: string): Promise<void> {\n // Specs are now in heraspec/specs/<changeName>/ instead of heraspec/changes/<changeName>/specs/\n const deltaSpecsDir = path.join(\n '.',\n HERASPEC_DIR_NAME,\n SPECS_DIR_NAME,\n changeName\n );\n \n if (!(await FileSystemUtils.fileExists(deltaSpecsDir))) {\n return; // No delta specs to merge\n }\n\n const deltaSpecs = await this.findDeltaSpecFiles(deltaSpecsDir);\n\n for (const deltaSpec of deltaSpecs) {\n // Calculate relative path from specs/<changeName>/\n const relativePath = path.relative(deltaSpecsDir, deltaSpec.path);\n // Target is in specs/ (source of truth), maintaining the same relative path structure\n const targetSpecPath = path.join(\n '.',\n HERASPEC_DIR_NAME,\n SPECS_DIR_NAME,\n relativePath\n );\n\n // Read delta spec\n const deltaContent = await FileSystemUtils.readFile(deltaSpec.path);\n const parser = new MarkdownParser(deltaContent);\n const delta = parser.parseDeltaSpec(deltaContent);\n\n // Read or create target spec\n let targetContent = '';\n if (await FileSystemUtils.fileExists(targetSpecPath)) {\n targetContent = await FileSystemUtils.readFile(targetSpecPath);\n }\n\n // Merge delta into target\n const mergedContent = this.mergeDeltaIntoSpec(targetContent, delta, deltaSpec.name);\n\n // Ensure directory exists\n await FileSystemUtils.createDirectory(path.dirname(targetSpecPath));\n\n // Write merged spec\n await FileSystemUtils.writeFile(targetSpecPath, mergedContent);\n }\n }\n\n private mergeDeltaIntoSpec(\n existingContent: string,\n delta: { added: any[]; modified: any[]; removed: any[] },\n specName: string\n ): string {\n // Simple merge implementation\n // In a real implementation, this would be more sophisticated\n \n let merged = existingContent || `# Spec: ${specName}\\n\\n## Purpose\\n\\n## Requirements\\n\\n`;\n\n // Add new requirements\n if (delta.added.length > 0) {\n merged += '\\n## ADDED Requirements\\n\\n';\n for (const req of delta.added) {\n merged += `### Requirement: ${req.name}\\n${req.description}\\n\\n`;\n }\n }\n\n // Note: Full merge logic would require more sophisticated parsing\n // For now, this is a basic implementation\n \n return merged;\n }\n\n private async moveChangeToArchive(sourcePath: string, archivePath: string): Promise<void> {\n const entries = await FileSystemUtils.readDirectory(sourcePath);\n\n for (const entry of entries) {\n const sourceEntry = path.join(sourcePath, entry);\n const archiveEntry = path.join(archivePath, entry);\n const stats = await FileSystemUtils.stat(sourceEntry);\n\n if (stats.isDirectory()) {\n await FileSystemUtils.createDirectory(archiveEntry);\n await this.moveChangeToArchive(sourceEntry, archiveEntry);\n } else {\n await FileSystemUtils.moveFile(sourceEntry, archiveEntry);\n }\n }\n }\n\n private async findDeltaSpecFiles(\n dir: string,\n prefix = ''\n ): Promise<Array<{ name: string; path: string }>> {\n const specs: Array<{ name: string; path: string }> = [];\n const entries = await FileSystemUtils.readDirectory(dir);\n\n for (const entry of entries) {\n const entryPath = path.join(dir, entry);\n const stats = await FileSystemUtils.stat(entryPath);\n\n if (stats.isDirectory()) {\n const subSpecs = await this.findDeltaSpecFiles(\n entryPath,\n prefix ? `${prefix}/${entry}` : entry\n );\n specs.push(...subSpecs);\n } else if (entry.endsWith('.md')) {\n specs.push({\n name: prefix || path.basename(entry, '.md'),\n path: entryPath,\n });\n }\n }\n\n return specs;\n }\n}\n\n", "/**\n * Markdown Parser for HeraSpec\n * Handles parsing of specs with Meta section, project types, and delta specs\n */\nimport { z } from 'zod';\nimport { Spec, RequirementSchema } from '../schemas/index.js';\nimport { SpecMeta } from '../config.js';\n\ninterface Section {\n level: number;\n title: string;\n content: string[];\n}\n\nexport class MarkdownParser {\n private lines: string[];\n\n constructor(content: string) {\n this.lines = MarkdownParser.normalizeContent(content).split('\\n');\n }\n\n protected static normalizeContent(content: string): string {\n return content.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n }\n\n parseSpec(name: string): Spec {\n const sections = this.parseSections();\n const meta = this.parseMeta(sections);\n const purpose = this.findSection(sections, 'Purpose')?.content.join('\\n').trim() || '';\n const requirementsSection = this.findSection(sections, 'Requirements');\n\n if (!purpose) {\n throw new Error('Spec must have a Purpose section');\n }\n\n if (!requirementsSection) {\n throw new Error('Spec must have a Requirements section');\n }\n\n const requirements = this.parseRequirements(requirementsSection);\n\n return {\n name,\n meta,\n overview: purpose.trim(),\n requirements,\n metadata: {\n version: '1.0.0',\n format: 'heraspec',\n },\n };\n }\n\n parseDeltaSpec(content: string): {\n added: any[];\n modified: any[];\n removed: any[];\n } {\n const sections = this.parseSections();\n const added = this.findSection(sections, 'ADDED Requirements');\n const modified = this.findSection(sections, 'MODIFIED Requirements');\n const removed = this.findSection(sections, 'REMOVED Requirements');\n\n return {\n added: added ? this.parseDeltaRequirements(added) : [],\n modified: modified ? this.parseDeltaRequirements(modified) : [],\n removed: removed ? this.parseDeltaRequirements(removed) : [],\n };\n }\n\n private parseMeta(sections: Section[]): SpecMeta | undefined {\n const metaSection = this.findSection(sections, 'Meta');\n if (!metaSection) {\n return undefined;\n }\n\n const meta: SpecMeta = {};\n const content = metaSection.content.join('\\n');\n\n // Parse project type\n const projectTypeMatch = content.match(/project type:\\s*(.+)/i);\n if (projectTypeMatch) {\n const types = projectTypeMatch[1].split('|').map(t => t.trim());\n meta.projectType = types.length === 1 ? types[0] : types;\n }\n\n // Parse domain\n const domainMatch = content.match(/domain:\\s*(.+)/i);\n if (domainMatch) {\n meta.domain = domainMatch[1].trim();\n }\n\n // Parse stack\n const stackMatch = content.match(/stack:\\s*(.+)/i);\n if (stackMatch) {\n const stacks = stackMatch[1].split('|').map(s => s.trim());\n meta.stack = stacks.length === 1 ? stacks[0] : stacks;\n }\n\n return Object.keys(meta).length > 0 ? meta : undefined;\n }\n\n private parseSections(): Section[] {\n const sections: Section[] = [];\n let currentSection: Section | null = null;\n\n for (const line of this.lines) {\n const headerMatch = line.match(/^(#{1,6})\\s+(.+)$/);\n if (headerMatch) {\n if (currentSection) {\n sections.push(currentSection);\n }\n currentSection = {\n level: headerMatch[1].length,\n title: headerMatch[2].trim(),\n content: [],\n };\n } else if (currentSection) {\n currentSection.content.push(line);\n }\n }\n\n if (currentSection) {\n sections.push(currentSection);\n }\n\n return sections;\n }\n\n private findSection(sections: Section[], title: string): Section | undefined {\n return sections.find(s => \n s.title.toLowerCase() === title.toLowerCase() ||\n s.title.toLowerCase().includes(title.toLowerCase())\n );\n }\n\n private parseRequirements(section: Section): z.infer<typeof RequirementSchema>[] {\n const requirements: z.infer<typeof RequirementSchema>[] = [];\n const lines = section.content;\n\n let currentRequirement: {\n name: string;\n description: string;\n scenarios: any[];\n constraints?: string[];\n } | null = null;\n\n let inRequirement = false;\n let inScenario = false;\n let currentScenario: { name: string; steps: string[] } | null = null;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n // Check for requirement header\n const reqMatch = line.match(/^###\\s+Requirement:\\s*(.+)$/i);\n if (reqMatch) {\n if (currentRequirement) {\n requirements.push(currentRequirement as any);\n }\n currentRequirement = {\n name: reqMatch[1].trim(),\n description: '',\n scenarios: [],\n };\n inRequirement = true;\n continue;\n }\n\n // Check for scenario header\n const scenarioMatch = line.match(/^####\\s+Scenario:\\s*(.+)$/i);\n if (scenarioMatch && currentRequirement) {\n if (currentScenario) {\n currentRequirement.scenarios.push(currentScenario);\n }\n currentScenario = {\n name: scenarioMatch[1].trim(),\n steps: [],\n };\n inScenario = true;\n continue;\n }\n\n // Check for GIVEN/WHEN/THEN steps\n if (currentScenario && (line.match(/^-\\s*(GIVEN|WHEN|THEN|AND|BUT)\\s+/i))) {\n const step = line.replace(/^-\\s*/, '').trim();\n currentScenario.steps.push(step);\n continue;\n }\n\n // Regular content line\n if (currentRequirement && !inScenario) {\n const trimmed = line.trim();\n if (trimmed && !trimmed.startsWith('#')) {\n currentRequirement.description += (currentRequirement.description ? '\\n' : '') + trimmed;\n }\n }\n }\n\n // Add final requirement and scenario\n if (currentScenario && currentRequirement) {\n currentRequirement.scenarios.push(currentScenario);\n }\n if (currentRequirement) {\n requirements.push(currentRequirement as any);\n }\n\n return requirements;\n }\n\n private parseDeltaRequirements(section: Section): any[] {\n // Similar to parseRequirements but expects ADDED/MODIFIED/REMOVED markers\n return this.parseRequirements(section);\n }\n}\n\n", "/**\n * HeraSpec Restore Command\n * Restores an archived change back to active changes\n */\nimport path from 'path';\nimport ora from 'ora';\nimport chalk from 'chalk';\nimport { FileSystemUtils } from '../utils/file-system.js';\nimport {\n HERASPEC_DIR_NAME,\n CHANGES_DIR_NAME,\n ARCHIVES_DIR_NAME,\n} from './config.js';\n\nexport class RestoreCommand {\n async execute(archiveName?: string, options?: { yes?: boolean }): Promise<void> {\n const archivesDir = path.join(\n '.',\n HERASPEC_DIR_NAME,\n CHANGES_DIR_NAME,\n ARCHIVES_DIR_NAME\n );\n\n // Check if archives directory exists\n if (!(await FileSystemUtils.fileExists(archivesDir))) {\n console.error('Error: No archives directory found. No archives to restore.');\n process.exitCode = 1;\n return;\n }\n\n // List available archives if name not provided\n if (!archiveName) {\n const archives = await this.listArchives(archivesDir);\n if (archives.length === 0) {\n console.log('No archived changes found.');\n return;\n }\n\n console.log('\\nAvailable archives:');\n console.log('\u2500'.repeat(60));\n archives.forEach((archive, index) => {\n console.log(`${index + 1}. ${archive}`);\n });\n console.log();\n console.error('Error: Please specify archive name to restore');\n console.log(`Usage: heraspec restore <archive-name>`);\n console.log(`Example: heraspec restore 2025-01-15-add-two-factor-auth`);\n process.exitCode = 1;\n return;\n }\n\n const archivePath = path.join(archivesDir, archiveName);\n\n // Check if archive exists\n if (!(await FileSystemUtils.fileExists(archivePath))) {\n console.error(`Error: Archive \"${archiveName}\" not found`);\n console.log('\\nAvailable archives:');\n const archives = await this.listArchives(archivesDir);\n archives.forEach((archive) => {\n console.log(` - ${archive}`);\n });\n process.exitCode = 1;\n return;\n }\n\n // Extract change name (remove date prefix)\n const changeName = this.extractChangeName(archiveName);\n const changePath = path.join(\n '.',\n HERASPEC_DIR_NAME,\n CHANGES_DIR_NAME,\n changeName\n );\n\n // Check if change already exists\n if (await FileSystemUtils.fileExists(changePath)) {\n console.error(`Error: Change \"${changeName}\" already exists in active changes.`);\n console.log('Please remove or rename the existing change first.');\n process.exitCode = 1;\n return;\n }\n\n // Confirm if not --yes\n if (!options?.yes) {\n console.log(`\\nThis will restore archive \"${archiveName}\" to active change \"${changeName}\".`);\n console.log('Note: This will not revert spec changes that were merged during archive.\\n');\n console.error('Error: Please use --yes flag to confirm');\n process.exitCode = 1;\n return;\n }\n\n const spinner = ora({\n text: `Restoring archive \"${archiveName}\"...`,\n color: 'blue',\n }).start();\n\n try {\n // Ensure changes directory exists\n const changesDir = path.join(\n '.',\n HERASPEC_DIR_NAME,\n CHANGES_DIR_NAME\n );\n await FileSystemUtils.createDirectory(changesDir);\n \n // Create destination directory first\n await FileSystemUtils.createDirectory(changePath);\n \n // Move archive back to changes directory\n await this.moveArchiveToChanges(archivePath, changePath);\n\n // Remove archive directory\n await FileSystemUtils.removeDirectory(archivePath, true);\n\n spinner.succeed(\n chalk.green(`Archive \"${archiveName}\" restored successfully to \"${changeName}\"`)\n );\n console.log();\n console.log(chalk.cyan('Note:'));\n console.log(\n chalk.gray(\n 'Spec changes that were merged during archive are still in source specs.'\n )\n );\n console.log(\n chalk.gray(\n 'You may need to manually review and revert spec changes if needed.'\n )\n );\n } catch (error) {\n spinner.fail(chalk.red(`Error: ${(error as Error).message}`));\n throw error;\n }\n }\n\n private async listArchives(archivesDir: string): Promise<string[]> {\n const archives: string[] = [];\n const entries = await FileSystemUtils.readDirectory(archivesDir);\n\n for (const entry of entries) {\n const entryPath = path.join(archivesDir, entry);\n const stats = await FileSystemUtils.stat(entryPath);\n if (stats.isDirectory()) {\n archives.push(entry);\n }\n }\n\n return archives.sort();\n }\n\n private extractChangeName(archiveName: string): string {\n // Remove date prefix (YYYY-MM-DD-)\n // Example: \"2025-01-15-add-two-factor-auth\" -> \"add-two-factor-auth\"\n const datePattern = /^\\d{4}-\\d{2}-\\d{2}-/;\n return archiveName.replace(datePattern, '');\n }\n\n private async moveArchiveToChanges(sourcePath: string, destPath: string): Promise<void> {\n const entries = await FileSystemUtils.readDirectory(sourcePath);\n\n for (const entry of entries) {\n const sourceEntry = path.join(sourcePath, entry);\n const destEntry = path.join(destPath, entry);\n const stats = await FileSystemUtils.stat(sourceEntry);\n\n if (stats.isDirectory()) {\n await FileSystemUtils.createDirectory(destEntry);\n await this.moveArchiveToChanges(sourceEntry, destEntry);\n } else {\n await FileSystemUtils.moveFile(sourceEntry, destEntry);\n }\n }\n }\n}\n\n", "/**\n * HeraSpec Show Command\n * Shows a change or spec in readable format\n */\nimport path from 'path';\nimport { readFileSync } from 'fs';\nimport chalk from 'chalk';\nimport { FileSystemUtils } from '../utils/file-system.js';\nimport { TaskParser } from '../utils/task-parser.js';\nimport {\n HERASPEC_DIR_NAME,\n CHANGES_DIR_NAME,\n SPECS_DIR_NAME,\n HERASPEC_MARKERS,\n} from '../core/config.js';\n\nexport class ShowCommand {\n async execute(itemName?: string): Promise<void> {\n if (!itemName) {\n console.error('Error: Please specify a change or spec name');\n console.log('Usage: heraspec show <change-name>');\n process.exitCode = 1;\n return;\n }\n\n // Try to find as change first\n const changePath = path.join(\n '.',\n HERASPEC_DIR_NAME,\n CHANGES_DIR_NAME,\n itemName\n );\n\n if (await FileSystemUtils.fileExists(changePath)) {\n await this.showChange(itemName, changePath);\n return;\n }\n\n // Try to find as spec\n const specPath = this.findSpecPath(itemName);\n if (specPath && (await FileSystemUtils.fileExists(specPath))) {\n await this.showSpec(specPath);\n return;\n }\n\n console.error(`Error: Change or spec \"${itemName}\" not found`);\n process.exitCode = 1;\n }\n\n private async showChange(changeName: string, changePath: string): Promise<void> {\n console.log(`\\n\uD83D\uDCCB Change: ${changeName}\\n`);\n console.log('\u2550'.repeat(60));\n\n // Show proposal\n const proposalPath = path.join(changePath, HERASPEC_MARKERS.PROPOSAL_MD);\n if (await FileSystemUtils.fileExists(proposalPath)) {\n console.log('\\n## Proposal\\n');\n const proposal = await FileSystemUtils.readFile(proposalPath);\n console.log(proposal);\n }\n\n // Show tasks\n const tasksPath = path.join(changePath, HERASPEC_MARKERS.TASKS_MD);\n if (await FileSystemUtils.fileExists(tasksPath)) {\n console.log('\\n## Tasks\\n');\n const tasks = await FileSystemUtils.readFile(tasksPath);\n console.log(tasks);\n\n // Show skills used in tasks\n try {\n const parsedTasks = TaskParser.parseTasks(tasksPath);\n if (parsedTasks.skillsUsed.length > 0) {\n console.log('\\n## Skills Used in This Change\\n');\n for (const skillInfo of parsedTasks.skillsUsed) {\n if (skillInfo.skill) {\n const skillLabel = skillInfo.projectType \n ? `${skillInfo.projectType}/${skillInfo.skill}`\n : skillInfo.skill;\n console.log(chalk.cyan(` \u2022 ${skillLabel}`));\n console.log(chalk.gray(` Location: heraspec/skills/${skillInfo.projectType ? skillInfo.projectType + '/' : ''}${skillInfo.skill}/`));\n }\n }\n console.log();\n console.log(chalk.yellow('\uD83D\uDCA1 Tip: Read skill.md files to understand how to implement tasks.'));\n console.log();\n }\n } catch (error) {\n // Ignore parsing errors\n }\n }\n\n // Show design if exists\n const designPath = path.join(changePath, HERASPEC_MARKERS.DESIGN_MD);\n if (await FileSystemUtils.fileExists(designPath)) {\n console.log('\\n## Design\\n');\n const design = await FileSystemUtils.readFile(designPath);\n console.log(design);\n }\n\n // Show delta specs (now in heraspec/specs/<changeName>/ instead of heraspec/changes/<changeName>/specs/)\n const specsPath = path.join(\n '.',\n HERASPEC_DIR_NAME,\n SPECS_DIR_NAME,\n changeName\n );\n if (await FileSystemUtils.fileExists(specsPath)) {\n const deltaSpecs = await this.findDeltaSpecs(specsPath);\n if (deltaSpecs.length > 0) {\n console.log('\\n## Delta Specs\\n');\n for (const spec of deltaSpecs) {\n console.log(`\\n### ${spec.name}\\n`);\n const content = await FileSystemUtils.readFile(spec.path);\n console.log(content);\n }\n }\n }\n\n console.log('\\n' + '\u2550'.repeat(60) + '\\n');\n }\n\n private async showSpec(specPath: string): Promise<void> {\n console.log('\\n\uD83D\uDCC4 Spec\\n');\n console.log('\u2550'.repeat(60));\n const content = await FileSystemUtils.readFile(specPath);\n console.log(content);\n console.log('\u2550'.repeat(60) + '\\n');\n }\n\n private findSpecPath(specName: string): string | null {\n // Try various path formats\n const basePath = path.join('.', HERASPEC_DIR_NAME, SPECS_DIR_NAME);\n const paths = [\n path.join(basePath, `${specName}.md`),\n path.join(basePath, specName, 'spec.md'),\n path.join(basePath, ...specName.split('/'), 'spec.md'),\n ];\n\n // Return first potential path (caller will check existence)\n return paths[0];\n }\n\n private async findDeltaSpecs(dir: string, prefix = ''): Promise<Array<{ name: string; path: string }>> {\n const specs: Array<{ name: string; path: string }> = [];\n const entries = await FileSystemUtils.readDirectory(dir);\n\n for (const entry of entries) {\n const entryPath = path.join(dir, entry);\n const stats = await FileSystemUtils.stat(entryPath);\n\n if (stats.isDirectory()) {\n const subSpecs = await this.findDeltaSpecs(\n entryPath,\n prefix ? `${prefix}/${entry}` : entry\n );\n specs.push(...subSpecs);\n } else if (entry === 'spec.md' || entry.endsWith('.md')) {\n specs.push({\n name: prefix || 'global',\n path: entryPath,\n });\n }\n }\n\n return specs;\n }\n}\n\n", "/**\n * Task Parser\n * Parses tasks.md to extract skill information\n */\nimport { readFileSync } from 'fs';\nimport { SkillManager } from '../core/skills/index.js';\n\nexport interface TaskGroup {\n title: string;\n projectType?: string;\n skill?: string;\n tasks: Array<{\n id: string;\n description: string;\n completed: boolean;\n }>;\n}\n\nexport interface ParsedTasks {\n groups: TaskGroup[];\n skillsUsed: Array<{ projectType?: string; skill: string }>;\n}\n\nexport class TaskParser {\n static parseTasks(filePath: string): ParsedTasks {\n const content = readFileSync(filePath, 'utf-8');\n const lines = content.split('\\n');\n\n const groups: TaskGroup[] = [];\n const skillsUsed = new Set<string>();\n let currentGroup: TaskGroup | null = null;\n\n for (const line of lines) {\n // Match task group header: ## 1. Title (projectType: xxx, skill: yyy)\n const groupMatch = line.match(/^##+\\s+\\d+\\.\\s+(.+?)\\s*\\((.+)\\)/);\n \n if (groupMatch) {\n // Save previous group\n if (currentGroup) {\n groups.push(currentGroup);\n }\n\n const title = groupMatch[1].trim();\n const params = groupMatch[2];\n \n // Extract projectType and skill\n const skillInfo = SkillManager.extractSkillFromTask(`(${params})`);\n \n currentGroup = {\n title,\n projectType: skillInfo?.projectType,\n skill: skillInfo?.skill,\n tasks: [],\n };\n\n if (skillInfo?.skill) {\n const skillKey = skillInfo.projectType \n ? `${skillInfo.projectType}:${skillInfo.skill}`\n : skillInfo.skill;\n skillsUsed.add(skillKey);\n }\n continue;\n }\n\n // Match task: - [ ] or - [x]\n const taskMatch = line.match(/^-\\s+\\[([ x])\\]\\s+(.+)/);\n if (taskMatch && currentGroup) {\n const completed = taskMatch[1] === 'x';\n const description = taskMatch[2].trim();\n \n // Extract task ID if present (e.g., \"1.1 Task description\")\n const idMatch = description.match(/^(\\d+\\.\\d+)\\s+/);\n const id = idMatch ? idMatch[1] : `${currentGroup.tasks.length + 1}`;\n const taskDesc = idMatch ? description.replace(/^\\d+\\.\\d+\\s+/, '') : description;\n\n currentGroup.tasks.push({\n id,\n description: taskDesc,\n completed,\n });\n }\n }\n\n // Save last group\n if (currentGroup) {\n groups.push(currentGroup);\n }\n\n // Convert skillsUsed set to array\n const skillsArray = Array.from(skillsUsed).map(skillKey => {\n const [projectType, skill] = skillKey.includes(':') \n ? skillKey.split(':')\n : [undefined, skillKey];\n return { projectType, skill };\n });\n\n return {\n groups,\n skillsUsed: skillsArray,\n };\n }\n\n static async getSkillsForTasks(filePath: string): Promise<Array<{ projectType?: string; skill: string; path: string }>> {\n const parsed = this.parseTasks(filePath);\n const skills: Array<{ projectType?: string; skill: string; path: string }> = [];\n\n for (const skillInfo of parsed.skillsUsed) {\n if (skillInfo.skill) {\n const skillPath = await SkillManager.findSkillPath(\n skillInfo.projectType || '',\n skillInfo.skill,\n '.'\n );\n \n if (skillPath) {\n skills.push({\n projectType: skillInfo.projectType,\n skill: skillInfo.skill,\n path: skillPath,\n });\n }\n }\n }\n\n return skills;\n }\n}\n\n", "/**\n * Skill Parser\n * Parses skill.md files to extract skill information\n */\nimport { readFileSync } from 'fs';\nimport path from 'path';\n\nexport interface SkillInfo {\n name: string;\n purpose: string;\n whenToUse: string[];\n steps: string[];\n inputs: string[];\n outputs: string[];\n toneAndRules: {\n codeStyle?: string;\n namingConventions?: string;\n limitations?: string[];\n };\n templates: string[];\n scripts: string[];\n examples: string[];\n relatedSkills: string[];\n skillPath: string;\n}\n\nexport class SkillParser {\n static parseSkill(skillPath: string, skillName: string): SkillInfo {\n const skillMdPath = path.join(skillPath, 'skill.md');\n \n try {\n const content = readFileSync(skillMdPath, 'utf-8');\n return this.parseSkillContent(content, skillName, skillPath);\n } catch (error) {\n throw new Error(`Failed to parse skill \"${skillName}\": ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n }\n\n private static parseSkillContent(content: string, skillName: string, skillPath: string): SkillInfo {\n const lines = content.split('\\n');\n \n const skill: Partial<SkillInfo> = {\n name: skillName,\n skillPath,\n purpose: '',\n whenToUse: [],\n steps: [],\n inputs: [],\n outputs: [],\n toneAndRules: {},\n templates: [],\n scripts: [],\n examples: [],\n relatedSkills: [],\n };\n\n let currentSection = '';\n let currentList: string[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim();\n \n // Detect section headers\n if (line.match(/^##+\\s+/)) {\n // Save previous list\n this.saveList(currentSection, currentList, skill);\n currentList = [];\n \n const sectionName = line.replace(/^##+\\s+/, '').toLowerCase();\n currentSection = sectionName;\n \n // Extract purpose\n if (sectionName.includes('m\u1EE5c \u0111\u00EDch') || sectionName.includes('purpose')) {\n // Purpose is usually the next line or paragraph\n if (i + 1 < lines.length && lines[i + 1].trim()) {\n skill.purpose = lines[i + 1].trim();\n }\n }\n continue;\n }\n\n // Collect list items\n if (line.startsWith('- ') || line.startsWith('* ')) {\n const item = line.replace(/^[-*]\\s+/, '').trim();\n if (item) {\n currentList.push(item);\n }\n continue;\n }\n\n // Collect numbered steps\n if (line.match(/^\\d+\\.\\s+/)) {\n const step = line.replace(/^\\d+\\.\\s+/, '').trim();\n if (step) {\n skill.steps = skill.steps || [];\n skill.steps.push(step);\n }\n continue;\n }\n\n // Extract specific fields\n if (currentSection.includes('input')) {\n if (line.startsWith('- ')) {\n skill.inputs = skill.inputs || [];\n skill.inputs.push(line.replace(/^-\\s+/, ''));\n }\n }\n\n if (currentSection.includes('output')) {\n if (line.startsWith('- ')) {\n skill.outputs = skill.outputs || [];\n skill.outputs.push(line.replace(/^-\\s+/, ''));\n }\n }\n\n if (currentSection.includes('template')) {\n if (line.includes('.php') || line.includes('.md') || line.includes('.scss') || line.includes('.js') || line.includes('.sh')) {\n skill.templates = skill.templates || [];\n const templateName = line.match(/`([^`]+)`/) || line.match(/\\*\\*([^*]+)\\*\\*/);\n if (templateName) {\n skill.templates.push(templateName[1]);\n }\n }\n }\n\n if (currentSection.includes('script')) {\n if (line.includes('.sh') || line.includes('.py') || line.includes('.js')) {\n skill.scripts = skill.scripts || [];\n const scriptName = line.match(/`([^`]+)`/) || line.match(/\\*\\*([^*]+)\\*\\*/);\n if (scriptName) {\n skill.scripts.push(scriptName[1]);\n }\n }\n }\n }\n\n // Save final list\n this.saveList(currentSection, currentList, skill);\n\n // Ensure all arrays exist\n return {\n name: skill.name || skillName,\n skillPath: skill.skillPath || skillPath,\n purpose: skill.purpose || 'No description available',\n whenToUse: skill.whenToUse || [],\n steps: skill.steps || [],\n inputs: skill.inputs || [],\n outputs: skill.outputs || [],\n toneAndRules: skill.toneAndRules || {},\n templates: skill.templates || [],\n scripts: skill.scripts || [],\n examples: skill.examples || [],\n relatedSkills: skill.relatedSkills || [],\n };\n }\n\n private static saveList(section: string, list: string[], skill: Partial<SkillInfo>): void {\n if (list.length === 0) return;\n\n if (section.includes('khi n\u00E0o') || section.includes('when')) {\n skill.whenToUse = list;\n } else if (section.includes('input')) {\n skill.inputs = list;\n } else if (section.includes('output')) {\n skill.outputs = list;\n } else if (section.includes('h\u1EA1n ch\u1EBF') || section.includes('limitation')) {\n skill.toneAndRules = skill.toneAndRules || {};\n skill.toneAndRules.limitations = list;\n } else if (section.includes('li\u00EAn k\u1EBFt') || section.includes('related')) {\n skill.relatedSkills = list;\n }\n }\n}\n\n", "/**\n * Skill Manager\n * Manages and discovers skills in a project\n */\nimport path from 'path';\nimport { FileSystemUtils } from '../../utils/file-system.js';\nimport { SkillParser, SkillInfo } from './skill-parser.js';\nimport { HERASPEC_DIR_NAME, SKILLS_DIR_NAME, PROJECT_TYPES, SKILLS } from '../config.js';\n\nexport class SkillManager {\n /**\n * Find skill path for a given project type and skill name\n */\n static async findSkillPath(\n projectType: string,\n skillName: string,\n projectPath: string = '.'\n ): Promise<string | null> {\n // Try project-specific skill first\n const projectSkillPath = path.join(\n projectPath,\n HERASPEC_DIR_NAME,\n SKILLS_DIR_NAME,\n projectType,\n skillName\n );\n\n if (await FileSystemUtils.fileExists(path.join(projectSkillPath, 'skill.md'))) {\n return projectSkillPath;\n }\n\n // Try cross-cutting skill\n const crossCuttingPath = path.join(\n projectPath,\n HERASPEC_DIR_NAME,\n SKILLS_DIR_NAME,\n skillName\n );\n\n if (await FileSystemUtils.fileExists(path.join(crossCuttingPath, 'skill.md'))) {\n return crossCuttingPath;\n }\n\n return null;\n }\n\n /**\n * Load skill information\n */\n static async loadSkill(\n projectType: string,\n skillName: string,\n projectPath: string = '.'\n ): Promise<SkillInfo | null> {\n const skillPath = await this.findSkillPath(projectType, skillName, projectPath);\n \n if (!skillPath) {\n return null;\n }\n\n try {\n return SkillParser.parseSkill(skillPath, skillName);\n } catch (error) {\n console.error(`Failed to load skill \"${skillName}\": ${error instanceof Error ? error.message : 'Unknown error'}`);\n return null;\n }\n }\n\n /**\n * List all available skills\n */\n static async listSkills(projectPath: string = '.'): Promise<Array<{ projectType?: string; skillName: string; path: string }>> {\n const skillsDir = path.join(projectPath, HERASPEC_DIR_NAME, SKILLS_DIR_NAME);\n \n if (!(await FileSystemUtils.fileExists(skillsDir))) {\n return [];\n }\n\n const skills: Array<{ projectType?: string; skillName: string; path: string }> = [];\n const entries = await FileSystemUtils.readDirectory(skillsDir);\n\n for (const entry of entries) {\n const entryPath = path.join(skillsDir, entry);\n const stats = await FileSystemUtils.stat(entryPath);\n\n if (stats.isDirectory()) {\n // Check if it's a project type folder or cross-cutting skill\n const isProjectType = PROJECT_TYPES.includes(entry as any);\n \n if (isProjectType) {\n // It's a project type folder, list skills inside\n const projectSkills = await this.listSkillsInDirectory(entryPath, entry);\n skills.push(...projectSkills);\n } else {\n // It's a cross-cutting skill\n const skillMdPath = path.join(entryPath, 'skill.md');\n if (await FileSystemUtils.fileExists(skillMdPath)) {\n skills.push({\n skillName: entry,\n path: entryPath,\n });\n }\n }\n }\n }\n\n return skills;\n }\n\n /**\n * Extract skill from task line\n */\n static extractSkillFromTask(taskLine: string): { projectType?: string; skill?: string } | null {\n // Match: (projectType: xxx, skill: yyy)\n const match = taskLine.match(/\\(projectType:\\s*([^,)]+)(?:,\\s*skill:\\s*([^)]+))?\\)/i);\n \n if (match) {\n return {\n projectType: match[1]?.trim(),\n skill: match[2]?.trim(),\n };\n }\n\n // Match: (skill: yyy)\n const skillOnlyMatch = taskLine.match(/\\(skill:\\s*([^)]+)\\)/i);\n if (skillOnlyMatch) {\n return {\n skill: skillOnlyMatch[1]?.trim(),\n };\n }\n\n return null;\n }\n\n private static async listSkillsInDirectory(\n dir: string,\n projectType: string\n ): Promise<Array<{ projectType: string; skillName: string; path: string }>> {\n const skills: Array<{ projectType: string; skillName: string; path: string }> = [];\n const entries = await FileSystemUtils.readDirectory(dir);\n\n for (const entry of entries) {\n const entryPath = path.join(dir, entry);\n const stats = await FileSystemUtils.stat(entryPath);\n\n if (stats.isDirectory()) {\n const skillMdPath = path.join(entryPath, 'skill.md');\n if (await FileSystemUtils.fileExists(skillMdPath)) {\n skills.push({\n projectType,\n skillName: entry,\n path: entryPath,\n });\n }\n }\n }\n\n return skills;\n }\n}\n\n", "/**\n * HeraSpec Validate Command\n */\nimport path from 'path';\nimport chalk from 'chalk';\nimport { FileSystemUtils } from '../utils/file-system.js';\nimport { Validator } from '../core/validation/validator.js';\nimport { HERASPEC_DIR_NAME, CHANGES_DIR_NAME, SPECS_DIR_NAME } from '../core/config.js';\n\nexport class ValidateCommand {\n async execute(itemName?: string, options?: { strict?: boolean }): Promise<void> {\n const validator = new Validator(options?.strict || false);\n\n if (!itemName) {\n console.error('Error: Please specify a change or spec name');\n console.log('Usage: heraspec validate <change-name>');\n process.exitCode = 1;\n return;\n }\n\n // Try change first\n const changePath = path.join('.', HERASPEC_DIR_NAME, CHANGES_DIR_NAME, itemName);\n if (await FileSystemUtils.fileExists(changePath)) {\n const report = await validator.validateChange(changePath);\n this.printReport(itemName, report);\n if (!report.valid) {\n process.exitCode = 1;\n }\n return;\n }\n\n // Try spec\n const specPath = this.findSpecPath(itemName);\n if (specPath && (await FileSystemUtils.fileExists(specPath))) {\n const report = await validator.validateSpec(specPath);\n this.printReport(itemName, report);\n if (!report.valid) {\n process.exitCode = 1;\n }\n return;\n }\n\n console.error(`Error: Change or spec \"${itemName}\" not found`);\n process.exitCode = 1;\n }\n\n private findSpecPath(specName: string): string | null {\n const basePath = path.join('.', HERASPEC_DIR_NAME, SPECS_DIR_NAME);\n return path.join(basePath, `${specName}.md`);\n }\n\n private printReport(itemName: string, report: any): void {\n console.log(`\\nValidation Report: ${itemName}\\n`);\n console.log('\u2500'.repeat(60));\n\n if (report.valid) {\n console.log(chalk.green('\u2713 Valid'));\n } else {\n console.log(chalk.red('\u2717 Invalid'));\n }\n\n if (report.errors && report.errors.length > 0) {\n console.log(chalk.red('\\nErrors:'));\n report.errors.forEach((err: any) => {\n console.log(chalk.red(` \u2022 ${err.message || err}`));\n if (err.suggestion) {\n console.log(chalk.gray(` \uD83D\uDCA1 Suggestion: ${err.suggestion}`));\n }\n if (err.path) {\n console.log(chalk.gray(` \uD83D\uDCCD Path: ${err.path}`));\n }\n });\n }\n\n if (report.warnings && report.warnings.length > 0) {\n console.log(chalk.yellow('\\nWarnings:'));\n report.warnings.forEach((warn: any) => {\n console.log(chalk.yellow(` \u2022 ${warn.message || warn}`));\n if (warn.suggestion) {\n console.log(chalk.gray(` \uD83D\uDCA1 Suggestion: ${warn.suggestion}`));\n }\n if (warn.path) {\n console.log(chalk.gray(` \uD83D\uDCCD Path: ${warn.path}`));\n }\n });\n }\n\n if (report.suggestions && report.suggestions.length > 0) {\n console.log(chalk.cyan('\\n\uD83D\uDCA1 Quick Fixes:'));\n report.suggestions.forEach((suggestion: string) => {\n console.log(chalk.cyan(` \u2022 ${suggestion}`));\n });\n }\n\n // Provide next steps if invalid\n if (!report.valid && report.errors && report.errors.length > 0) {\n console.log(chalk.gray('\\n\uD83D\uDCDD Next Steps:'));\n console.log(chalk.gray(' 1. Review errors above'));\n console.log(chalk.gray(' 2. Apply suggested fixes'));\n console.log(chalk.gray(' 3. Run validation again: heraspec validate ' + itemName));\n }\n\n console.log('\\n' + '\u2500'.repeat(60) + '\\n');\n }\n}\n\n", "/**\n * HeraSpec Validator\n * Validates specs and changes\n */\nimport { readFileSync } from 'fs';\nimport path from 'path';\nimport { SpecSchema, ChangeSchema } from '../schemas/index.js';\nimport { MarkdownParser } from '../parsers/markdown-parser.js';\nimport { FileSystemUtils } from '../../utils/file-system.js';\nimport { HERASPEC_DIR_NAME, SPECS_DIR_NAME } from '../config.js';\n\nexport interface ValidationIssue {\n message: string;\n path?: string;\n line?: number;\n suggestion?: string;\n autoFixable?: boolean;\n}\n\nexport interface ValidationReport {\n valid: boolean;\n errors: ValidationIssue[];\n warnings: ValidationIssue[];\n suggestions?: string[];\n}\n\nexport class Validator {\n private strictMode: boolean;\n\n constructor(strictMode: boolean = false) {\n this.strictMode = strictMode;\n }\n\n async validateSpec(filePath: string): Promise<ValidationReport> {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n try {\n const content = readFileSync(filePath, 'utf-8');\n const parser = new MarkdownParser(content);\n const specName = this.extractNameFromPath(filePath);\n const spec = parser.parseSpec(specName);\n\n // Validate against schema\n const result = SpecSchema.safeParse(spec);\n\n if (!result.success) {\n result.error.errors.forEach((err) => {\n errors.push(`${err.path.join('.')}: ${err.message}`);\n });\n }\n\n // Additional validation rules\n if (spec.requirements.length === 0) {\n errors.push('Spec must have at least one requirement');\n }\n\n for (const req of spec.requirements) {\n if (!req.description || req.description.trim().length === 0) {\n errors.push(`Requirement \"${req.name}\" must have a description`);\n }\n\n if (!req.scenarios || req.scenarios.length === 0) {\n warnings.push(`Requirement \"${req.name}\" has no scenarios`);\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n } catch (error) {\n return {\n valid: false,\n errors: [error instanceof Error ? error.message : 'Unknown error'],\n warnings: [],\n };\n }\n }\n\n async validateChange(changePath: string): Promise<ValidationReport> {\n const errors: ValidationIssue[] = [];\n const warnings: ValidationIssue[] = [];\n const suggestions: string[] = [];\n\n // Check for proposal.md\n const proposalPath = path.join(changePath, 'proposal.md');\n if (!(await FileSystemUtils.fileExists(proposalPath))) {\n errors.push({\n message: 'Change must have a proposal.md file',\n path: proposalPath,\n suggestion: `Create proposal.md in ${changePath} with: # Change Proposal: [name]\\n\\n## Purpose\\n[Description]\\n\\n## Scope\\n[What will change]`,\n autoFixable: false,\n });\n suggestions.push(`Create proposal.md file at ${proposalPath}`);\n }\n\n // Check for tasks.md\n const tasksPath = path.join(changePath, 'tasks.md');\n if (!(await FileSystemUtils.fileExists(tasksPath))) {\n warnings.push({\n message: 'Change has no tasks.md file',\n path: tasksPath,\n suggestion: `Create tasks.md with implementation tasks grouped by project type and skill`,\n autoFixable: false,\n });\n }\n\n // Validate delta specs if they exist\n // Specs are now in heraspec/specs/<changeName>/ instead of heraspec/changes/<changeName>/specs/\n const changeName = path.basename(changePath);\n const specsDir = path.join(\n '.',\n HERASPEC_DIR_NAME,\n SPECS_DIR_NAME,\n changeName\n );\n if (await FileSystemUtils.fileExists(specsDir)) {\n const deltaSpecs = await this.findDeltaSpecs(specsDir);\n for (const specPath of deltaSpecs) {\n const report = await this.validateDeltaSpec(specPath);\n errors.push(...report.errors);\n warnings.push(...report.warnings);\n if (report.suggestions) {\n suggestions.push(...report.suggestions);\n }\n }\n } else {\n warnings.push({\n message: 'No delta specs found for this change',\n suggestion: `Create delta specs in ${specsDir}/spec.md using ADDED/MODIFIED/REMOVED sections`,\n autoFixable: false,\n });\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n suggestions: suggestions.length > 0 ? suggestions : undefined,\n };\n }\n\n private async validateDeltaSpec(filePath: string): Promise<ValidationReport> {\n const errors: ValidationIssue[] = [];\n const warnings: ValidationIssue[] = [];\n const suggestions: string[] = [];\n\n try {\n const content = readFileSync(filePath, 'utf-8');\n const parser = new MarkdownParser(content);\n const delta = parser.parseDeltaSpec(content);\n\n // Check that delta has at least one section\n if (delta.added.length === 0 && delta.modified.length === 0 && delta.removed.length === 0) {\n warnings.push({\n message: 'Delta spec has no changes',\n suggestion: 'Add at least one section: ## ADDED Requirements, ## MODIFIED Requirements, or ## REMOVED Requirements',\n autoFixable: false,\n });\n }\n\n // Check for proper delta format\n if (!content.includes('## ADDED') && !content.includes('## MODIFIED') && !content.includes('## REMOVED')) {\n warnings.push({\n message: 'Delta spec may not follow proper format',\n suggestion: 'Use sections: ## ADDED Requirements, ## MODIFIED Requirements, ## REMOVED Requirements',\n autoFixable: false,\n });\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n suggestions: suggestions.length > 0 ? suggestions : undefined,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n const suggestion = this.getParseErrorSuggestion(errorMessage);\n \n return {\n valid: false,\n errors: [{\n message: errorMessage,\n suggestion,\n autoFixable: false,\n }],\n warnings: [],\n suggestions: suggestion ? [suggestion] : undefined,\n };\n }\n }\n\n private extractNameFromPath(filePath: string): string {\n const baseName = path.basename(filePath, '.md');\n return baseName === 'spec' ? path.basename(path.dirname(filePath)) : baseName;\n }\n\n private async findDeltaSpecs(dir: string): Promise<string[]> {\n const specs: string[] = [];\n const entries = await FileSystemUtils.readDirectory(dir);\n\n for (const entry of entries) {\n const entryPath = path.join(dir, entry);\n const stats = await FileSystemUtils.stat(entryPath);\n\n if (stats.isDirectory()) {\n const subSpecs = await this.findDeltaSpecs(entryPath);\n specs.push(...subSpecs);\n } else if (entry.endsWith('.md')) {\n specs.push(entryPath);\n }\n }\n\n return specs;\n }\n}\n\n", "/**\n * Base schemas for HeraSpec\n */\nimport { z } from 'zod';\n\nexport const ProjectTypeSchema = z.enum([\n 'wordpress-plugin',\n 'wordpress-theme',\n 'perfex-module',\n 'laravel-package',\n 'node-service',\n 'generic-webapp',\n 'backend-api',\n 'frontend-app',\n 'multi-stack',\n]);\n\nexport const SpecMetaSchema = z.object({\n projectType: z.union([\n ProjectTypeSchema,\n z.array(ProjectTypeSchema),\n ]).optional(),\n domain: z.string().optional(),\n stack: z.union([\n z.string(),\n z.array(z.string()),\n ]).optional(),\n}).optional();\n\nexport const ScenarioSchema = z.object({\n name: z.string(),\n steps: z.array(z.string()).min(1),\n});\n\nexport const RequirementSchema = z.object({\n id: z.string().optional(),\n name: z.string(),\n description: z.string(),\n scenarios: z.array(ScenarioSchema).optional(),\n constraints: z.array(z.string()).optional(),\n});\n\n", "/**\n * HeraSpec Specification Schema\n */\nimport { z } from 'zod';\nimport { RequirementSchema, SpecMetaSchema } from './base.schema.js';\n\nexport const SpecSchema = z.object({\n name: z.string().min(1),\n meta: SpecMetaSchema,\n overview: z.string().min(1),\n requirements: z.array(RequirementSchema).min(1),\n metadata: z.object({\n version: z.string().default('1.0.0'),\n format: z.literal('heraspec'),\n sourcePath: z.string().optional(),\n }).optional(),\n});\n\nexport type Spec = z.infer<typeof SpecSchema>;\n\n", "/**\n * HeraSpec Change Schema\n */\nimport { z } from 'zod';\n\nexport const DeltaTypeSchema = z.enum(['ADDED', 'MODIFIED', 'REMOVED']);\n\nexport const DeltaRequirementSchema = z.object({\n type: DeltaTypeSchema,\n requirement: z.object({\n id: z.string().optional(),\n name: z.string(),\n description: z.string(),\n scenarios: z.array(z.object({\n name: z.string(),\n steps: z.array(z.string()),\n })).optional(),\n constraints: z.array(z.string()).optional(),\n }),\n});\n\nexport const ChangeSchema = z.object({\n name: z.string(),\n proposal: z.string().min(1),\n tasks: z.array(z.string()).optional(),\n design: z.string().optional(),\n});\n\nexport type Change = z.infer<typeof ChangeSchema>;\nexport type DeltaRequirement = z.infer<typeof DeltaRequirementSchema>;\n\n", "/**\n * HeraSpec Skill Command\n * Shows skill information, lists available skills, repairs, and adds skills\n */\nimport path from 'path';\nimport { readFileSync } from 'fs';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { FileSystemUtils } from '../utils/file-system.js';\nimport { SkillManager, SkillParser } from '../core/skills/index.js';\nimport { HERASPEC_DIR_NAME, SKILLS_DIR_NAME, PROJECT_TYPES } from '../core/config.js';\nimport { getSkillTemplateInfo, getAllSkillTemplates } from '../core/templates/skills-template-map.js';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { createRequire } from 'module';\n\nconst require = createRequire(import.meta.url);\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n// Get HeraSpec core templates directory\n// Try multiple paths to handle both source and built versions, and installed packages\nasync function getCoreTemplatesDir(): Promise<string | null> {\n const possiblePaths: string[] = [];\n \n // Strategy 1: Resolve package.json from current file location (works when bundled)\n // When running from bin/heraspec.js, this resolves to the package root\n try {\n const packageJsonPath = require.resolve('../package.json');\n const packageDir = path.dirname(packageJsonPath);\n \n possiblePaths.push(\n join(packageDir, 'src', 'core', 'templates', 'skills'), // Source (when linked, this is the actual source)\n join(packageDir, 'dist', 'core', 'templates', 'skills'), // Built (templates copied during build)\n );\n } catch {\n // Could not resolve, continue\n }\n \n // Strategy 2: Try require.resolve('heraspec/package.json') for npm installed packages\n try {\n const packageJsonPath = require.resolve('heraspec/package.json');\n const packageDir = path.dirname(packageJsonPath);\n \n possiblePaths.push(\n join(packageDir, 'dist', 'core', 'templates', 'skills'), // Built\n join(packageDir, 'src', 'core', 'templates', 'skills'), // Source (if available)\n );\n } catch {\n // Package not found, continue\n }\n \n // Strategy 3: Relative paths from current file location (when running from source)\n possiblePaths.push(\n // Source version (for development) - when running from source: src/commands/skill.ts\n join(__dirname, '..', '..', 'src', 'core', 'templates', 'skills'),\n // Built version - when running from built: dist/commands/skill.js\n join(__dirname, '..', 'core', 'templates', 'skills'),\n // Alternative: from project root (when running from HeraSpec source)\n join(process.cwd(), 'src', 'core', 'templates', 'skills'),\n );\n\n for (const possiblePath of possiblePaths) {\n if (await FileSystemUtils.fileExists(possiblePath)) {\n return possiblePath;\n }\n }\n\n return null;\n}\n\nexport class SkillCommand {\n async list(projectPath: string = '.'): Promise<void> {\n const skills = await SkillManager.listSkills(projectPath);\n\n if (skills.length === 0) {\n console.log('No skills found. Skills will be created as needed.');\n console.log('See docs/SKILLS_STRUCTURE_PROPOSAL.md for skill structure.');\n return;\n }\n\n console.log('\\nAvailable Skills:\\n');\n console.log('\u2550'.repeat(60));\n\n // Group by project type\n const byProjectType: Record<string, Array<{ skillName: string; path: string }>> = {};\n const crossCutting: Array<{ skillName: string; path: string }> = [];\n\n for (const skill of skills) {\n if (skill.projectType) {\n if (!byProjectType[skill.projectType]) {\n byProjectType[skill.projectType] = [];\n }\n byProjectType[skill.projectType].push({\n skillName: skill.skillName,\n path: skill.path,\n });\n } else {\n crossCutting.push({\n skillName: skill.skillName,\n path: skill.path,\n });\n }\n }\n\n // Display project-specific skills\n for (const [projectType, projectSkills] of Object.entries(byProjectType)) {\n console.log(`\\n\uD83D\uDCE6 ${projectType}:`);\n for (const skill of projectSkills) {\n console.log(` \u2022 ${skill.skillName}`);\n }\n }\n\n // Display cross-cutting skills\n if (crossCutting.length > 0) {\n console.log(`\\n\uD83D\uDD27 Cross-cutting skills:`);\n for (const skill of crossCutting) {\n console.log(` \u2022 ${skill.skillName}`);\n }\n }\n\n console.log('\\n' + '\u2550'.repeat(60) + '\\n');\n }\n\n async show(skillName: string, projectType?: string, projectPath: string = '.'): Promise<void> {\n if (!skillName) {\n console.error('Error: Please specify a skill name');\n console.log('Usage: heraspec skill show <skill-name> [--project-type <type>]');\n process.exitCode = 1;\n return;\n }\n\n // Try to find skill\n let skillInfo = null;\n \n if (projectType) {\n skillInfo = await SkillManager.loadSkill(projectType, skillName, projectPath);\n } else {\n // Try to find in any project type\n const skills = await SkillManager.listSkills(projectPath);\n const found = skills.find(s => s.skillName === skillName);\n \n if (found) {\n try {\n skillInfo = SkillParser.parseSkill(found.path, skillName);\n } catch (error) {\n console.error(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exitCode = 1;\n return;\n }\n }\n }\n\n if (!skillInfo) {\n console.error(`Error: Skill \"${skillName}\" not found`);\n if (projectType) {\n console.log(`Searched in: heraspec/skills/${projectType}/${skillName}/`);\n } else {\n console.log('Searched in: heraspec/skills/');\n }\n process.exitCode = 1;\n return;\n }\n\n // Display skill information\n console.log(`\\n\uD83D\uDCDA Skill: ${skillInfo.name}\\n`);\n console.log('\u2550'.repeat(60));\n\n console.log(`\\n\uD83D\uDCCD Path: ${skillInfo.skillPath}\\n`);\n\n if (skillInfo.purpose) {\n console.log('## Purpose');\n console.log(skillInfo.purpose);\n console.log();\n }\n\n if (skillInfo.whenToUse.length > 0) {\n console.log('## When to Use');\n skillInfo.whenToUse.forEach(item => {\n console.log(`- ${item}`);\n });\n console.log();\n }\n\n if (skillInfo.steps.length > 0) {\n console.log('## Steps');\n skillInfo.steps.forEach((step, index) => {\n console.log(`${index + 1}. ${step}`);\n });\n console.log();\n }\n\n if (skillInfo.inputs.length > 0) {\n console.log('## Inputs');\n skillInfo.inputs.forEach(input => {\n console.log(`- ${input}`);\n });\n console.log();\n }\n\n if (skillInfo.outputs.length > 0) {\n console.log('## Outputs');\n skillInfo.outputs.forEach(output => {\n console.log(`- ${output}`);\n });\n console.log();\n }\n\n if (skillInfo.templates.length > 0) {\n console.log('## Available Templates');\n skillInfo.templates.forEach(template => {\n console.log(`- ${template}`);\n });\n console.log();\n }\n\n if (skillInfo.scripts.length > 0) {\n console.log('## Available Scripts');\n skillInfo.scripts.forEach(script => {\n console.log(`- ${script}`);\n });\n console.log();\n }\n\n if (skillInfo.toneAndRules.limitations && skillInfo.toneAndRules.limitations.length > 0) {\n console.log('## Limitations');\n skillInfo.toneAndRules.limitations.forEach(limitation => {\n console.log(`- ${limitation}`);\n });\n console.log();\n }\n\n // Show full skill.md content\n const skillMdPath = path.join(skillInfo.skillPath, 'skill.md');\n if (await FileSystemUtils.fileExists(skillMdPath)) {\n console.log('\u2550'.repeat(60));\n console.log('\\n## Full skill.md Content\\n');\n const content = await FileSystemUtils.readFile(skillMdPath);\n console.log(content);\n }\n\n console.log('\\n' + '\u2550'.repeat(60) + '\\n');\n }\n\n async repair(projectPath: string = '.'): Promise<void> {\n const spinner = ora('Repairing skills structure...').start();\n\n try {\n const skillsDir = path.join(projectPath, HERASPEC_DIR_NAME, SKILLS_DIR_NAME);\n \n if (!(await FileSystemUtils.fileExists(skillsDir))) {\n spinner.fail('Skills directory does not exist. Run \"heraspec init\" first.');\n process.exitCode = 1;\n return;\n }\n\n const skills = await SkillManager.listSkills(projectPath);\n let fixed = 0;\n let errors = 0;\n\n for (const skill of skills) {\n const skillPath = skill.path;\n const skillMdPath = path.join(skillPath, 'skill.md');\n\n // Ensure skill.md exists\n if (!(await FileSystemUtils.fileExists(skillMdPath))) {\n spinner.warn(`Missing skill.md in ${skillPath}`);\n errors++;\n continue;\n }\n\n // Ensure standard directories exist\n const standardDirs = ['templates', 'scripts', 'examples'];\n for (const dir of standardDirs) {\n const dirPath = path.join(skillPath, dir);\n if (!(await FileSystemUtils.fileExists(dirPath))) {\n await FileSystemUtils.createDirectory(dirPath);\n fixed++;\n }\n }\n\n // Validate skill.md structure (basic check)\n try {\n const content = await FileSystemUtils.readFile(skillMdPath);\n if (!content.includes('## Purpose') && !content.includes('# Skill:')) {\n spinner.warn(`Invalid skill.md structure in ${skillPath}`);\n }\n } catch (error) {\n spinner.warn(`Cannot read skill.md in ${skillPath}: ${error instanceof Error ? error.message : 'Unknown error'}`);\n errors++;\n }\n }\n\n if (errors === 0 && fixed === 0) {\n spinner.succeed('All skills are properly structured');\n } else {\n spinner.succeed(`Repaired ${fixed} issues, found ${errors} errors`);\n }\n } catch (error) {\n spinner.fail(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exitCode = 1;\n }\n }\n\n async add(skillName: string, projectType?: string, projectPath: string = '.'): Promise<void> {\n if (!skillName) {\n console.error('Error: Please specify a skill name');\n console.log('Usage: heraspec skills add <skill-name> [--project-type <type>]');\n process.exitCode = 1;\n return;\n }\n\n const spinner = ora(`Adding skill \"${skillName}\"...`).start();\n\n try {\n // Get template info\n const templateInfo = getSkillTemplateInfo(skillName, projectType);\n \n if (!templateInfo) {\n spinner.fail(`Skill template \"${skillName}\" not found`);\n console.log('\\nAvailable skills:');\n const allTemplates = getAllSkillTemplates();\n for (const { skillName: name, projectType: pt } of allTemplates) {\n if (pt) {\n console.log(` - ${name} (projectType: ${pt})`);\n } else {\n console.log(` - ${name} (cross-cutting)`);\n }\n }\n process.exitCode = 1;\n return;\n }\n\n // Determine destination path\n const skillsDir = path.join(projectPath, HERASPEC_DIR_NAME, SKILLS_DIR_NAME);\n \n let destPath: string;\n if (templateInfo.isCrossCutting) {\n destPath = path.join(skillsDir, skillName);\n } else {\n if (!templateInfo.projectType) {\n spinner.fail('Project type is required for this skill');\n process.exitCode = 1;\n return;\n }\n \n let effectiveSkillName = skillName;\n if (skillName.includes(':')) {\n const parts = skillName.split(':');\n if (parts.length === 2 && parts[0] === templateInfo.projectType) {\n effectiveSkillName = parts[1];\n }\n }\n \n destPath = path.join(skillsDir, templateInfo.projectType, effectiveSkillName);\n\n // Cleanup legacy prefixed folder if it exists (e.g., heraspec/skills/wordpress/wordpress:plugin-check)\n const legacyPath = path.join(skillsDir, templateInfo.projectType, `${templateInfo.projectType}:${effectiveSkillName}`);\n if (legacyPath !== destPath && await FileSystemUtils.fileExists(legacyPath)) {\n spinner.info(`Cleaning up legacy prefixed skill folder: ${legacyPath}`);\n try {\n await FileSystemUtils.removeDirectory(legacyPath, true);\n } catch (cleanupError) {\n spinner.warn(`Could not remove legacy folder ${legacyPath}: ${cleanupError instanceof Error ? cleanupError.message : 'Unknown error'}`);\n }\n }\n }\n\n // Check if already exists - remove old skill before adding new one\n const isUpdate = await FileSystemUtils.fileExists(destPath);\n if (isUpdate) {\n spinner.info(`Skill \"${skillName}\" already exists at ${destPath}`);\n spinner.start(`Removing old version to update with latest...`);\n try {\n await FileSystemUtils.removeDirectory(destPath, true);\n spinner.succeed(`Removed old skill \"${skillName}\"`);\n } catch (error) {\n spinner.fail(`Failed to remove old skill: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exitCode = 1;\n return;\n }\n spinner.start(`Adding updated skill \"${skillName}\"...`);\n }\n\n // Ensure directories exist\n await FileSystemUtils.createDirectory(destPath);\n\n // Get core templates directory\n const coreTemplatesDir = await getCoreTemplatesDir();\n if (!coreTemplatesDir) {\n spinner.fail('Cannot find HeraSpec templates directory. Make sure you are running from HeraSpec project or have templates installed.');\n process.exitCode = 1;\n return;\n }\n\n const templateFile = path.join(coreTemplatesDir, templateInfo.templateFileName);\n\n // Check if template file exists\n if (!(await FileSystemUtils.fileExists(templateFile))) {\n spinner.fail(`Template file not found: ${templateFile}`);\n process.exitCode = 1;\n return;\n }\n\n await FileSystemUtils.copyFile(templateFile, path.join(destPath, 'skill.md'));\n\n // Copy resource directories if specified\n if (templateInfo.resourceDirs) {\n for (const resourceDir of templateInfo.resourceDirs) {\n const srcResourceDir = path.join(coreTemplatesDir, resourceDir);\n const destResourceDir = path.join(destPath, resourceDir);\n \n if (await FileSystemUtils.fileExists(srcResourceDir)) {\n await FileSystemUtils.copyDirectory(srcResourceDir, destResourceDir);\n }\n }\n }\n\n // Create standard directories\n await FileSystemUtils.createDirectory(path.join(destPath, 'templates'));\n await FileSystemUtils.createDirectory(path.join(destPath, 'scripts'));\n await FileSystemUtils.createDirectory(path.join(destPath, 'examples'));\n\n const successMessage = isUpdate \n ? `Skill \"${skillName}\" updated successfully`\n : `Skill \"${skillName}\" added successfully`;\n \n spinner.succeed(successMessage);\n console.log(`\\n\uD83D\uDCCD Location: ${destPath}`);\n if (isUpdate) {\n console.log(`\\n\u2728 Skill has been updated with latest features and improvements.`);\n }\n console.log(`\\n\uD83D\uDCA1 Run \"heraspec skill show ${skillName}${projectType ? ` --project-type ${projectType}` : ''}\" to view details\\n`);\n } catch (error) {\n spinner.fail(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exitCode = 1;\n }\n }\n\n async update(skillName: string, projectType?: string, projectPath: string = '.'): Promise<void> {\n // The internal logic of add already handles updating existing skills by removing the old version first\n return this.add(skillName, projectType, projectPath);\n }\n}\n", "/**\n * Skills Template Mapping\n * Maps skill names to their template files and resources\n */\nexport interface SkillTemplateInfo {\n templateFileName: string; // Just the filename, path resolved at runtime\n isCrossCutting: boolean;\n projectType?: string;\n resourceDirs?: string[]; // Additional directories to copy (e.g., scripts, templates, data)\n}\n\n/**\n * Mapping of skill names to their template information\n * Key format: \"projectType:skillName\" for project-specific, or \"skillName\" for cross-cutting\n */\nexport const SKILL_TEMPLATE_MAP: Record<string, SkillTemplateInfo> = {\n // Cross-cutting skills\n 'ui-ux': {\n templateFileName: 'ui-ux-skill.md',\n isCrossCutting: true,\n resourceDirs: ['scripts', 'templates', 'data'],\n },\n 'documents': {\n templateFileName: 'documents-skill.md',\n isCrossCutting: true,\n resourceDirs: ['documents/templates'],\n },\n 'content-optimization': {\n templateFileName: 'content-optimization-skill.md',\n isCrossCutting: true,\n },\n 'unit-test': {\n templateFileName: 'unit-test-skill.md',\n isCrossCutting: true,\n },\n 'integration-test': {\n templateFileName: 'integration-test-skill.md',\n isCrossCutting: true,\n },\n 'e2e-test': {\n templateFileName: 'e2e-test-skill.md',\n isCrossCutting: true,\n },\n 'suggestion': {\n templateFileName: 'suggestion-skill.md',\n isCrossCutting: true,\n },\n \n // Perfex module skills\n 'perfex-module:module-codebase': {\n templateFileName: 'module-codebase-skill.md',\n isCrossCutting: false,\n projectType: 'perfex-module',\n },\n 'wordpress:ux-element': {\n templateFileName: 'ux-element-skill.md',\n isCrossCutting: false,\n projectType: 'wordpress',\n resourceDirs: ['ux-element/templates'],\n },\n 'wordpress:plugin-standard': {\n templateFileName: 'wordpress-plugin-standard-skill.md',\n isCrossCutting: false,\n projectType: 'wordpress',\n resourceDirs: ['wordpress-plugin-standard/templates'],\n },\n 'wordpress:plugin-check': {\n templateFileName: 'wordpress-plugin-check-skill.md',\n isCrossCutting: false,\n projectType: 'wordpress',\n },\n 'wordpress:plugin-directory': {\n templateFileName: 'plugin-directory-skill.md',\n isCrossCutting: false,\n projectType: 'wordpress',\n },\n // WordPress Plugin specific (matches PROJECT_TYPES)\n 'wordpress-plugin:plugin-check': {\n templateFileName: 'wordpress-plugin-check-skill.md',\n isCrossCutting: false,\n projectType: 'wordpress-plugin',\n },\n 'wordpress-plugin:plugin-directory': {\n templateFileName: 'plugin-directory-skill.md',\n isCrossCutting: false,\n projectType: 'wordpress-plugin',\n },\n};\n\n/**\n * Get template info for a skill\n */\nexport function getSkillTemplateInfo(skillName: string, projectType?: string): SkillTemplateInfo | null {\n // Try project-specific first\n if (projectType) {\n const key = `${projectType}:${skillName}`;\n if (SKILL_TEMPLATE_MAP[key]) {\n return SKILL_TEMPLATE_MAP[key];\n }\n }\n \n // Try cross-cutting\n if (SKILL_TEMPLATE_MAP[skillName]) {\n return SKILL_TEMPLATE_MAP[skillName];\n }\n \n // If we haven't found it and no projectType was specified, assume inferred lookup\n if (!projectType) {\n for (const key of Object.keys(SKILL_TEMPLATE_MAP)) {\n // Check if key is \"projectType:skillName\"\n const parts = key.split(':');\n if (parts.length === 2 && parts[1] === skillName) {\n return SKILL_TEMPLATE_MAP[key];\n }\n }\n }\n \n return null;\n}\n\n/**\n * Get all available skill templates\n */\nexport function getAllSkillTemplates(): Array<{ skillName: string; projectType?: string; info: SkillTemplateInfo }> {\n const result: Array<{ skillName: string; projectType?: string; info: SkillTemplateInfo }> = [];\n \n for (const [key, info] of Object.entries(SKILL_TEMPLATE_MAP)) {\n if (info.isCrossCutting) {\n result.push({ skillName: key, info });\n } else {\n const [projectType, skillName] = key.split(':');\n result.push({ skillName, projectType, info });\n }\n }\n \n return result;\n}\n\n", "/**\n * HeraSpec Helper Command\n * Displays usage guides, example prompts, and workflow instructions\n */\n\nimport chalk from 'chalk';\n\nexport class HelperCommand {\n async execute(): Promise<void> {\n console.log(chalk.cyan.bold('\\n\uD83D\uDCDA HeraSpec Helper - Usage Guide\\n'));\n console.log('\u2550'.repeat(70) + '\\n');\n\n this.showQuickStart();\n this.showCommands();\n this.showExamplePrompts();\n this.showWorkflow();\n this.showTips();\n\n console.log('\\n' + '\u2550'.repeat(70));\n console.log(chalk.gray('\\n\uD83D\uDCA1 Tip: See details at docs/README.md (available in multiple languages)\\n'));\n }\n\n private showQuickStart(): void {\n console.log(chalk.yellow.bold('\uD83D\uDE80 Quick Start\\n'));\n console.log(chalk.white('1. Initialize a new project:'));\n console.log(chalk.gray(' cd my-project'));\n console.log(chalk.cyan(' heraspec init\\n'));\n\n console.log(chalk.white('2. Configure project.md:'));\n console.log(chalk.gray(' Edit heraspec/project.md with your project information\\n'));\n\n console.log(chalk.white('3. Create your first change (using AI):'));\n console.log(chalk.cyan(' \"Create a HeraSpec change to add feature X\"\\n'));\n\n console.log(chalk.white('4. View list:'));\n console.log(chalk.cyan(' heraspec list\\n'));\n\n console.log('\u2500'.repeat(70) + '\\n');\n }\n\n private showCommands(): void {\n console.log(chalk.yellow.bold('\u26A1 Main CLI Commands\\n'));\n \n const commands = [\n { cmd: 'heraspec init [path]', desc: 'Initialize HeraSpec in project' },\n { cmd: 'heraspec list', desc: 'List changes (default)' },\n { cmd: 'heraspec list --specs', desc: 'List specs' },\n { cmd: 'heraspec skills', desc: 'List all available skills (shortcut)' },\n { cmd: 'heraspec show [name]', desc: 'Show change or spec details' },\n { cmd: 'heraspec validate [name]', desc: 'Validate change or spec' },\n { cmd: 'heraspec archive [name]', desc: 'Archive completed change' },\n { cmd: 'heraspec restore [name]', desc: 'Restore change from archive' },\n { cmd: 'heraspec skill list', desc: 'List available skills' },\n { cmd: 'heraspec skill show <name>', desc: 'Show skill details' },\n { cmd: 'heraspec make docs', desc: 'Generate product documentation' },\n { cmd: 'heraspec make docs --agent <name>', desc: 'Generate docs with AI agent' },\n { cmd: 'heraspec make test', desc: 'Generate test cases from specs' },\n { cmd: 'heraspec make test --type <type>', desc: 'Generate tests (unit/integration/e2e)' },\n { cmd: 'heraspec suggest', desc: 'Suggest new features for project' },\n { cmd: 'heraspec view', desc: 'View dashboard overview' },\n { cmd: 'heraspec helper', desc: 'Show this guide' },\n ];\n\n commands.forEach(({ cmd, desc }) => {\n console.log(chalk.cyan(` ${cmd.padEnd(35)}`) + chalk.white(desc));\n });\n\n console.log('\\n' + '\u2500'.repeat(70) + '\\n');\n }\n\n private showExamplePrompts(): void {\n console.log(chalk.yellow.bold('\uD83D\uDCAC Example Prompts for AI\\n'));\n\n console.log(chalk.white.bold('1. Simple Change Creation:\\n'));\n console.log(chalk.gray(' \"Create a HeraSpec change to add 2FA authentication feature\"\\n'));\n console.log(chalk.gray(' \"Create HeraSpec change for order management module\"\\n'));\n\n console.log(chalk.white.bold('2. Create Change Based on project.md:\\n'));\n console.log(chalk.gray(' \"Read heraspec/project.md and create HeraSpec changes for all\\n'));\n console.log(chalk.gray(' features mentioned in it\"\\n'));\n console.log(chalk.gray(' \"Based on project.md, create changes to implement by phase\"\\n'));\n\n console.log(chalk.white.bold('3. Detailed Change Creation:\\n'));\n console.log(chalk.gray(' \"Create HeraSpec change with the following steps:\\n'));\n console.log(chalk.gray(' 1. Read and analyze heraspec/project.md\\n'));\n console.log(chalk.gray(' 2. Identify features to build\\n'));\n console.log(chalk.gray(' 3. For each feature, create a separate change\\n'));\n console.log(chalk.gray(' 4. Each change needs proposal.md, tasks.md, specs/\\n'));\n console.log(chalk.gray(' 5. Follow conventions in project.md\"\\n'));\n\n console.log(chalk.white.bold('4. Prompt With Project Type and Skill:\\n'));\n console.log(chalk.gray(' \"Create change for WordPress plugin with skill admin-settings-page\"\\n'));\n console.log(chalk.gray(' \"Create change for Perfex module with skill module-codebase\"\\n'));\n console.log(chalk.gray(' \"Create UI/UX change with skill ui-ux for admin interface\"\\n'));\n\n console.log(chalk.white.bold('5. View and Validate:\\n'));\n console.log(chalk.gray(' \"View change add-user-auth\"\\n'));\n console.log(chalk.gray(' \"Validate change add-user-auth --strict\"\\n'));\n console.log(chalk.gray(' \"List all changes\"\\n'));\n\n console.log(chalk.white.bold('6. Implementation:\\n'));\n console.log(chalk.gray(' \"Specs approved, start implementing change add-user-auth\"\\n'));\n console.log(chalk.gray(' \"Execute tasks in change add-user-auth\"\\n'));\n\n console.log(chalk.white.bold('7. Generate Documentation:\\n'));\n console.log(chalk.gray(' \"Generate product documentation from specs\"\\n'));\n console.log(chalk.gray(' heraspec make docs\\n'));\n console.log(chalk.gray(' \"Generate docs with specific AI agent\"\\n'));\n console.log(chalk.gray(' heraspec make docs --agent chatgpt\\n'));\n console.log(chalk.gray(' heraspec make docs --agent claude\\n'));\n \n console.log(chalk.white.bold('8. Multi-Format Documentation (Skill: Documents):\\n'));\n console.log(chalk.gray(' \"Generate documentation with skill documents for [project-name]. Include:\\n'));\n console.log(chalk.gray(' - Concise overview (documentation.txt)\\n'));\n console.log(chalk.gray(' - Technical Markdown (documentation.md)\\n'));\n console.log(chalk.gray(' - Interactive HTML Documentation (documentation.html)\\n'));\n console.log(chalk.gray(' - Premium Documentation Landing Page (documentation-landing-page.html)\"\\n'));\n console.log(chalk.gray(' \"Use documents skill to create dynamic, project-specific docs\"\\n'));\n\n console.log(chalk.gray(' \"Use test skills: unit-test, integration-test, e2e-test for test implementation\"'));\n\n console.log(chalk.white.bold('9. WordPress Plugin Check:\\n'));\n console.log(chalk.gray(' \"Use skill plugin-check to check, then resolve *all* issues mentioned for plugin `[TARGET_PLUGIN]`\"\\n'));\n console.log(chalk.gray(' \"Ensure careful handling and verify that related features still function correctly.\"\\n'));\n\n console.log('\u2500'.repeat(70) + '\\n');\n }\n\n private showWorkflow(): void {\n console.log(chalk.yellow.bold('\uD83D\uDD04 Workflow\\n'));\n\n const steps = [\n {\n step: '1. Create Change',\n actions: [\n 'AI or you create change directory',\n 'Write proposal.md describing purpose',\n 'Create tasks.md with task list',\n 'Write delta specs in specs/',\n ],\n prompt: '\"Create HeraSpec change to...\"',\n },\n {\n step: '2. Refine Specs',\n actions: [\n 'Review: heraspec show <name>',\n 'Ask AI to edit if needed',\n 'Validate: heraspec validate <name>',\n ],\n prompt: '\"Edit specs in change...\"',\n },\n {\n step: '3. Approval',\n actions: ['Wait for user: \"Specs approved.\"'],\n prompt: 'You confirm: \"Specs approved.\"',\n },\n {\n step: '4. Implementation',\n actions: [\n 'AI reads tasks.md and skill.md',\n 'Execute each task',\n 'Mark completed: - [x]',\n ],\n prompt: '\"Specs approved, implement change...\"',\n },\n {\n step: '5. Archive',\n actions: [\n 'Review: heraspec show <name>',\n 'Archive: heraspec archive <name> --yes',\n 'Specs merged into source specs',\n ],\n prompt: 'heraspec archive <name> --yes',\n },\n {\n step: '6. Generate Documentation',\n actions: [\n 'Generate basic docs: heraspec make docs',\n 'Use Skill Documents: \"Generate documentation with skill documents\"',\n 'Outputs: documentation.txt, .md, .html, and landing-page.html',\n 'Agent uses ui-ux skill for premium dynamic design',\n ],\n prompt: '\"Generate documentation with skill documents for [project-name]\"',\n },\n {\n step: '7. Quality Check (Plugin Check)',\n actions: [\n 'Run Plugin Check: \"Use skill plugin-check...\"',\n 'Agent iterates until all issues resolved',\n 'Safety check: Verify features functionality',\n ],\n prompt: '\"Use skill plugin-check to check plugin [target-plugin]\"',\n },\n ];\n\n steps.forEach(({ step, actions, prompt }) => {\n console.log(chalk.cyan.bold(` ${step}`));\n actions.forEach((action) => {\n console.log(chalk.white(` \u2022 ${action}`));\n });\n console.log(chalk.gray(` \uD83D\uDCAC ${prompt}\\n`));\n });\n\n console.log('\u2500'.repeat(70) + '\\n');\n }\n\n private showTips(): void {\n console.log(chalk.yellow.bold('\uD83D\uDCA1 Tips & Best Practices\\n'));\n\n const tips = [\n 'Always read heraspec/project.md before creating change',\n 'Use Skills system when implementing (each task has skill tag)',\n 'Validate specs before requesting approval',\n 'One change should focus on one specific feature',\n 'Name change: kebab-case, verb-led (add-, create-, implement-)',\n 'Delta specs only change in change folder',\n 'Do not edit source-of-truth specs directly',\n 'Archive change after completion to merge specs',\n 'Use heraspec skill list to view available skills',\n 'UI/UX tasks: Use search scripts in skill ui-ux',\n 'Premium Documentation: Use \"skill documents\" for txt, md, html, and landing page',\n 'Dynamic Docs: Documents skill generates custom layouts based on your project specs',\n 'Generate product docs: heraspec make docs (default agent: chatgpt)',\n 'Specify AI agent: heraspec make docs --agent <name> (chatgpt, claude, etc.)',\n 'Generate tests: heraspec make test (default: unit)',\n 'Test types: unit (individual functions), integration (components), e2e (user flows)',\n 'Generate code: heraspec make code (generates code skeletons from specs)',\n 'Validate with suggestions: heraspec validate <name> (includes fix suggestions)',\n 'Get feature suggestions: heraspec suggest (analyzes project and suggests enhancements)',\n 'Use test skills: unit-test, integration-test, e2e-test for test implementation',\n 'Plugin Check: Use \"skill plugin-check\" to ensure code quality and safety',\n ];\n\n tips.forEach((tip) => {\n console.log(chalk.white(` \u2022 ${tip}`));\n });\n\n console.log('');\n }\n}\n", "/**\n * HeraSpec Make Docs Command\n * Generates user-friendly product documentation from specs\n */\nimport path from 'path';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { FileSystemUtils } from '../utils/file-system.js';\nimport { HERASPEC_DIR_NAME, SPECS_DIR_NAME, HERASPEC_MARKERS } from '../core/config.js';\n\nexport class MakeDocsCommand {\n async execute(projectPath: string = '.', agent: string = 'chatgpt'): Promise<void> {\n const spinner = ora(`Generating product documentation (Agent: ${agent})...`).start();\n\n try {\n const resolvedPath = path.resolve(projectPath);\n const specsDir = path.join(resolvedPath, HERASPEC_DIR_NAME, SPECS_DIR_NAME);\n const docsDir = path.join(resolvedPath, 'documentations');\n const projectMdPath = path.join(resolvedPath, HERASPEC_DIR_NAME, HERASPEC_MARKERS.PROJECT_MD);\n\n // Check if specs directory exists\n if (!(await FileSystemUtils.fileExists(specsDir))) {\n spinner.fail('Specs directory not found. Run \"heraspec init\" first.');\n process.exitCode = 1;\n return;\n }\n\n // Ensure documentation directory exists\n await FileSystemUtils.createDirectory(docsDir);\n\n // Read project.md if exists (for context)\n let projectInfo: { name?: string; description?: string } = {};\n if (await FileSystemUtils.fileExists(projectMdPath)) {\n const projectContent = await FileSystemUtils.readFile(projectMdPath);\n projectInfo = this.extractProjectInfo(projectContent);\n }\n\n // Check for Skills\n const hasDocumentsSkill = await FileSystemUtils.fileExists(path.join(resolvedPath, HERASPEC_DIR_NAME, 'skills', 'documents'));\n const hasUIUXSkill = await FileSystemUtils.fileExists(path.join(resolvedPath, HERASPEC_DIR_NAME, 'skills', 'ui-ux'));\n\n // Find all spec files\n const specFiles = await this.findSpecFiles(specsDir);\n\n if (specFiles.length === 0) {\n spinner.warn('No specs found. Create specs first using \"heraspec list --specs\".');\n return;\n }\n\n // Read and parse all specs\n const specs = await this.readSpecs(specFiles);\n\n // Generate user-friendly documentation\n const docContent = this.generateProductDocumentation(specs, projectInfo, agent);\n\n // Write documentation file\n const docFilePath = path.join(docsDir, 'documentation.txt');\n await FileSystemUtils.writeFile(docFilePath, docContent);\n\n spinner.succeed(`Basic documentation generated: ${docFilePath}`);\n\n if (hasDocumentsSkill) {\n console.log(chalk.green.bold('\\n\u2728 Documents Skill Detected!'));\n console.log(chalk.white('AI Agent Instruction:'));\n console.log(chalk.gray(' \"Now use the documents skill to generate the full multi-format package:'));\n console.log(chalk.gray(' - Use documentation.txt as context'));\n console.log(chalk.gray(' - Create documentation.md, documentation.html, and landing page'));\n console.log(chalk.gray(' - CRITICAL: Save all files in the /documentations directory (create it if missing)'));\n if (hasUIUXSkill) {\n console.log(chalk.gray(' - Apply premium design from the ui-ux skill standards\"'));\n } else {\n console.log(chalk.yellow(' - WARNING: \"ui-ux\" skill is MISSING but required for HTML/Landing Page.'));\n console.log(chalk.gray(' - Agent must install it first: heraspec skill add ui-ux\"'));\n }\n } else {\n console.log(chalk.yellow('\\n\uD83D\uDCA1 Tip: Add the \"documents\" skill for premium HTML & Landing Page support:'));\n console.log(chalk.gray(' heraspec skill add documents'));\n }\n\n console.log(chalk.gray(`\\nFound ${specFiles.length} feature(s)`));\n } catch (error) {\n spinner.fail(`Error: ${(error as Error).message}`);\n process.exitCode = 1;\n throw error;\n }\n }\n\n /**\n * Extract project information from project.md\n */\n private extractProjectInfo(projectContent: string): { name?: string; description?: string } {\n const info: { name?: string; description?: string } = {};\n \n // Extract project name (usually first heading or after # Project Name)\n const nameMatch = projectContent.match(/^#\\s+(.+)$/m);\n if (nameMatch) {\n info.name = nameMatch[1].trim();\n }\n\n // Extract description (first paragraph after title)\n const lines = projectContent.split('\\n');\n let descriptionStart = false;\n const descriptionLines: string[] = [];\n \n for (const line of lines) {\n if (line.startsWith('#') && !descriptionStart) {\n descriptionStart = true;\n continue;\n }\n if (descriptionStart && line.trim() && !line.startsWith('#')) {\n descriptionLines.push(line.trim());\n if (descriptionLines.length >= 3) break; // Get first few lines\n }\n }\n \n if (descriptionLines.length > 0) {\n info.description = descriptionLines.join(' ');\n }\n\n return info;\n }\n\n /**\n * Find all spec files recursively\n */\n private async findSpecFiles(specsDir: string): Promise<string[]> {\n const specFiles: string[] = [];\n await this.findSpecFilesRecursive(specsDir, specFiles);\n return specFiles.sort();\n }\n\n /**\n * Recursively find spec files\n */\n private async findSpecFilesRecursive(dir: string, files: string[]): Promise<void> {\n const fs = await import('fs/promises');\n const entries = await fs.readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n await this.findSpecFilesRecursive(entryPath, files);\n } else if (entry.name.endsWith('.md')) {\n files.push(entryPath);\n }\n }\n }\n\n /**\n * Read all spec files\n */\n private async readSpecs(specFiles: string[]): Promise<Array<{ path: string; content: string; name: string }>> {\n const specs = [];\n\n for (const specFile of specFiles) {\n const content = await FileSystemUtils.readFile(specFile);\n const name = this.extractFeatureName(specFile, content);\n\n specs.push({\n path: specFile,\n content,\n name,\n });\n }\n\n return specs;\n }\n\n /**\n * Extract feature name from spec file\n */\n private extractFeatureName(filePath: string, content: string): string {\n // Try to get from first heading\n const headingMatch = content.match(/^#+\\s+(.+)$/m);\n if (headingMatch) {\n return headingMatch[1].trim();\n }\n \n // Fallback to filename\n return path.basename(filePath, '.md')\n .split('-')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n }\n\n /**\n * Generate product documentation from specs\n */\n private generateProductDocumentation(\n specs: Array<{ path: string; content: string; name: string }>,\n projectInfo: { name?: string; description?: string },\n agent: string = 'chatgpt'\n ): string {\n const lines: string[] = [];\n\n // Title\n const productName = projectInfo.name || 'Product';\n lines.push(`# ${productName}`);\n lines.push('');\n\n // Description\n if (projectInfo.description) {\n lines.push(projectInfo.description);\n lines.push('');\n }\n\n lines.push('---');\n lines.push('');\n\n // Overview\n lines.push('## Overview');\n lines.push('');\n lines.push(`This product includes ${specs.length} main feature${specs.length > 1 ? 's' : ''}:`);\n lines.push('');\n specs.forEach((spec, index) => {\n lines.push(`${index + 1}. ${spec.name}`);\n });\n lines.push('');\n lines.push('---');\n lines.push('');\n\n // Features (user-friendly descriptions)\n lines.push('## Features');\n lines.push('');\n\n specs.forEach((spec, index) => {\n const featureInfo = this.extractFeatureInfo(spec.content);\n \n lines.push(`### ${index + 1}. ${spec.name}`);\n lines.push('');\n\n // Purpose/Description\n if (featureInfo.description) {\n lines.push(featureInfo.description);\n lines.push('');\n }\n\n // Key Capabilities\n if (featureInfo.capabilities.length > 0) {\n lines.push('**Key Capabilities:**');\n lines.push('');\n featureInfo.capabilities.forEach(cap => {\n lines.push(`- ${cap}`);\n });\n lines.push('');\n }\n\n // Use Cases (if any scenarios)\n if (featureInfo.useCases.length > 0) {\n lines.push('**Use Cases:**');\n lines.push('');\n featureInfo.useCases.forEach(useCase => {\n lines.push(`- ${useCase}`);\n });\n lines.push('');\n }\n\n if (index < specs.length - 1) {\n lines.push('---');\n lines.push('');\n }\n });\n\n // Footer\n lines.push('');\n lines.push('---');\n lines.push('');\n lines.push(`*This documentation is auto-generated from product specifications using ${agent}.*`);\n lines.push('');\n\n return lines.join('\\n');\n }\n\n /**\n * Extract user-friendly information from spec content\n */\n private extractFeatureInfo(content: string): {\n description: string;\n capabilities: string[];\n useCases: string[];\n } {\n const info: { description: string; capabilities: string[]; useCases: string[] } = {\n description: '',\n capabilities: [],\n useCases: [],\n };\n\n const lines = content.split('\\n');\n let inPurpose = false;\n let inRequirements = false;\n let inScenarios = false;\n let currentSection = '';\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const trimmed = line.trim();\n\n // Detect sections\n if (trimmed.match(/^##+\\s+Purpose/i)) {\n inPurpose = true;\n inRequirements = false;\n inScenarios = false;\n continue;\n } else if (trimmed.match(/^##+\\s+Requirements?/i)) {\n inPurpose = false;\n inRequirements = true;\n inScenarios = false;\n continue;\n } else if (trimmed.match(/^##+\\s+Scenarios?/i)) {\n inPurpose = false;\n inRequirements = false;\n inScenarios = true;\n continue;\n } else if (trimmed.match(/^##+/)) {\n // New section, stop current\n inPurpose = false;\n inRequirements = false;\n inScenarios = false;\n continue;\n }\n\n // Extract Purpose as description\n if (inPurpose && trimmed && !trimmed.startsWith('#')) {\n if (!info.description) {\n info.description = trimmed;\n } else if (info.description.length < 300) {\n info.description += ' ' + trimmed;\n }\n }\n\n // Extract Requirements as capabilities\n if (inRequirements && trimmed.startsWith('-')) {\n const requirement = trimmed.replace(/^-\\s*/, '').trim();\n if (requirement) {\n // Clean up technical terms, make user-friendly\n const userFriendly = this.makeUserFriendly(requirement);\n info.capabilities.push(userFriendly);\n }\n }\n\n // Extract Scenarios as use cases\n if (inScenarios && trimmed.match(/^[*-]\\s*.+:/)) {\n const scenario = trimmed.replace(/^[*-]\\s*/, '').split(':')[0].trim();\n if (scenario) {\n const userFriendly = this.makeUserFriendly(scenario);\n info.useCases.push(userFriendly);\n }\n }\n }\n\n // If no description found, use first paragraph\n if (!info.description) {\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed && !trimmed.startsWith('#') && trimmed.length > 20) {\n info.description = trimmed;\n break;\n }\n }\n }\n\n return info;\n }\n\n /**\n * Make technical text more user-friendly\n */\n private makeUserFriendly(text: string): string {\n // Remove technical markers\n let result = text\n .replace(/\\([^)]*\\)/g, '') // Remove parentheses\n .replace(/\\[([^\\]]+)\\]/g, '$1') // Convert [text] to text\n .replace(/\\{([^}]+)\\}/g, '$1') // Convert {text} to text\n .replace(/\\b(GET|POST|PUT|DELETE|API|REST|HTTP)\\b/gi, '') // Remove API terms\n .replace(/\\b(endpoint|route|method|parameter|query|body)\\b/gi, '') // Remove technical terms\n .trim();\n\n // Capitalize first letter\n if (result) {\n result = result.charAt(0).toUpperCase() + result.slice(1);\n }\n\n // Clean up multiple spaces\n result = result.replace(/\\s+/g, ' ');\n\n return result;\n }\n}\n", "/**\n * HeraSpec Make Test Command\n * Generates test cases for project features\n */\nimport path from 'path';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { FileSystemUtils } from '../utils/file-system.js';\nimport { HERASPEC_DIR_NAME, SPECS_DIR_NAME, HERASPEC_MARKERS } from '../core/config.js';\n\nexport class MakeTestCommand {\n async execute(projectPath: string = '.', testType: string = 'unit'): Promise<void> {\n const spinner = ora(`Generating ${testType} tests...`).start();\n\n try {\n const resolvedPath = path.resolve(projectPath);\n const specsDir = path.join(resolvedPath, HERASPEC_DIR_NAME, SPECS_DIR_NAME);\n const projectMdPath = path.join(resolvedPath, HERASPEC_DIR_NAME, HERASPEC_MARKERS.PROJECT_MD);\n\n // Check if specs directory exists\n if (!(await FileSystemUtils.fileExists(specsDir))) {\n spinner.fail('Specs directory not found. Run \"heraspec init\" first.');\n process.exitCode = 1;\n return;\n }\n\n // Determine test directory based on project type (can be customized)\n const testDir = this.getTestDirectory(resolvedPath, testType);\n\n // Ensure test directory exists\n await FileSystemUtils.createDirectory(testDir);\n\n // Read project.md if exists\n let projectInfo: { projectType?: string; stack?: string[] } = {};\n if (await FileSystemUtils.fileExists(projectMdPath)) {\n const projectContent = await FileSystemUtils.readFile(projectMdPath);\n projectInfo = this.extractProjectInfo(projectContent);\n }\n\n // Find all spec files\n const specFiles = await this.findSpecFiles(specsDir);\n\n if (specFiles.length === 0) {\n spinner.warn('No specs found. Create specs first using \"heraspec list --specs\".');\n return;\n }\n\n // Read and parse all specs\n const specs = await this.readSpecs(specFiles);\n\n // Generate test files\n const testFilesCreated = await this.generateTestFiles(specs, testDir, testType, projectInfo);\n\n spinner.succeed(`Generated ${testFilesCreated.length} test file(s) in ${testDir}`);\n console.log(chalk.gray(`\\nTest type: ${testType}`));\n console.log(chalk.gray(`Specs analyzed: ${specFiles.length}`));\n } catch (error) {\n spinner.fail(`Error: ${(error as Error).message}`);\n process.exitCode = 1;\n throw error;\n }\n }\n\n /**\n * Get test directory path based on project type and test type\n */\n private getTestDirectory(projectPath: string, testType: string): string {\n // Default test directories\n const testDirs: Record<string, string> = {\n unit: 'tests/unit',\n integration: 'tests/integration',\n e2e: 'tests/e2e',\n };\n\n const baseDir = testDirs[testType] || 'tests';\n return path.join(projectPath, baseDir);\n }\n\n /**\n * Extract project information from project.md\n */\n private extractProjectInfo(projectContent: string): { projectType?: string; stack?: string[] } {\n const info: { projectType?: string; stack?: string[] } = {};\n\n // Extract project type\n const projectTypeMatch = projectContent.match(/project[-\\s]type[s]?[:\\s]+([^\\n]+)/i);\n if (projectTypeMatch) {\n info.projectType = projectTypeMatch[1].trim();\n }\n\n // Extract tech stack\n const stackMatch = projectContent.match(/tech[-\\s]stack[:\\s]+([^\\n]+)/i);\n if (stackMatch) {\n info.stack = stackMatch[1]\n .split(',')\n .map(s => s.trim())\n .filter(s => s.length > 0);\n }\n\n return info;\n }\n\n /**\n * Find all spec files recursively\n */\n private async findSpecFiles(specsDir: string): Promise<string[]> {\n const specFiles: string[] = [];\n await this.findSpecFilesRecursive(specsDir, specFiles);\n return specFiles.sort();\n }\n\n /**\n * Recursively find spec files\n */\n private async findSpecFilesRecursive(dir: string, files: string[]): Promise<void> {\n const fs = await import('fs/promises');\n const entries = await fs.readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n await this.findSpecFilesRecursive(entryPath, files);\n } else if (entry.name.endsWith('.md')) {\n files.push(entryPath);\n }\n }\n }\n\n /**\n * Read all spec files\n */\n private async readSpecs(specFiles: string[]): Promise<Array<{ path: string; content: string; name: string }>> {\n const specs = [];\n\n for (const specFile of specFiles) {\n const content = await FileSystemUtils.readFile(specFile);\n const name = this.extractFeatureName(specFile, content);\n\n specs.push({\n path: specFile,\n content,\n name,\n });\n }\n\n return specs;\n }\n\n /**\n * Extract feature name from spec file\n */\n private extractFeatureName(filePath: string, content: string): string {\n // Try to get from first heading\n const headingMatch = content.match(/^#+\\s+(.+)$/m);\n if (headingMatch) {\n return headingMatch[1].trim();\n }\n\n // Fallback to filename\n return path.basename(filePath, '.md');\n }\n\n /**\n * Generate test files from specs\n */\n private async generateTestFiles(\n specs: Array<{ path: string; content: string; name: string }>,\n testDir: string,\n testType: string,\n projectInfo: { projectType?: string; stack?: string[] }\n ): Promise<string[]> {\n const createdFiles: string[] = [];\n\n for (const spec of specs) {\n const testFileName = this.getTestFileName(spec.name, testType, projectInfo);\n const testFilePath = path.join(testDir, testFileName);\n\n // Check if file already exists\n if (await FileSystemUtils.fileExists(testFilePath)) {\n console.log(chalk.yellow(` \u2139 Skipping ${path.basename(testFilePath)} - already exists.`));\n continue;\n }\n\n const testContent = this.generateTestContent(spec, testType, projectInfo);\n await FileSystemUtils.writeFile(testFilePath, testContent);\n createdFiles.push(testFilePath);\n }\n\n return createdFiles;\n }\n\n /**\n * Generate test file content\n */\n private generateTestContent(\n spec: { path: string; content: string; name: string },\n testType: string,\n projectInfo: { projectType?: string; stack?: string[] }\n ): string {\n const featureInfo = this.extractFeatureInfo(spec.content);\n const testFramework = this.determineTestFramework(projectInfo);\n\n const lines: string[] = [];\n\n // Header comment\n lines.push(`/**`);\n lines.push(` * ${testType.charAt(0).toUpperCase() + testType.slice(1)} tests for: ${spec.name}`);\n lines.push(` * Generated from spec: ${path.basename(spec.path)}`);\n lines.push(` */`);\n lines.push('');\n\n // Test framework setup\n if (testFramework === 'jest') {\n lines.push(`describe('${spec.name}', () => {`);\n lines.push(' // TODO: Implement test cases based on spec requirements');\n lines.push('');\n if (featureInfo.requirements.length > 0) {\n featureInfo.requirements.forEach((req, index) => {\n lines.push(` test('should ${req}', () => {`);\n lines.push(` // Test implementation needed`);\n lines.push(` expect(true).toBe(true);`);\n lines.push(` });`);\n if (index < featureInfo.requirements.length - 1) {\n lines.push('');\n }\n });\n }\n lines.push('});');\n } else if (testFramework === 'phpunit') {\n lines.push(`class ${this.toPascalCase(spec.name)}Test extends TestCase`);\n lines.push('{');\n lines.push(' // TODO: Implement test cases based on spec requirements');\n lines.push('');\n if (featureInfo.requirements.length > 0) {\n featureInfo.requirements.forEach((req, index) => {\n lines.push(` public function test_${this.toSnakeCase(req)}()`);\n lines.push(' {');\n lines.push(' // Test implementation needed');\n lines.push(' $this->assertTrue(true);');\n lines.push(' }');\n if (index < featureInfo.requirements.length - 1) {\n lines.push('');\n }\n });\n }\n lines.push('}');\n } else {\n // Generic test structure\n lines.push(`// ${testType.charAt(0).toUpperCase() + testType.slice(1)} tests for: ${spec.name}`);\n lines.push('');\n lines.push('// TODO: Implement test cases based on spec requirements');\n lines.push('');\n if (featureInfo.requirements.length > 0) {\n featureInfo.requirements.forEach((req) => {\n lines.push(`// Test: ${req}`);\n });\n }\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Determine test framework based on project info\n */\n private determineTestFramework(projectInfo: { projectType?: string; stack?: string[] }): string {\n if (projectInfo.stack) {\n if (projectInfo.stack.some(s => s.toLowerCase().includes('php'))) {\n return 'phpunit';\n }\n if (projectInfo.stack.some(s => s.toLowerCase().includes('node') || s.toLowerCase().includes('javascript'))) {\n return 'jest';\n }\n }\n\n // Default to jest for modern projects\n return 'jest';\n }\n\n /**\n * Get test file name\n */\n private getTestFileName(featureName: string, testType: string, projectInfo: { projectType?: string; stack?: string[] }): string {\n const framework = this.determineTestFramework(projectInfo);\n const baseName = this.toKebabCase(featureName);\n\n if (framework === 'phpunit') {\n return `${this.toPascalCase(featureName)}Test.php`;\n } else if (framework === 'jest') {\n return `${baseName}.test.js`;\n }\n\n return `${baseName}.test.js`;\n }\n\n /**\n * Extract feature info from spec content\n */\n private extractFeatureInfo(content: string): { requirements: string[] } {\n const info: { requirements: string[] } = {\n requirements: [],\n };\n\n const lines = content.split('\\n');\n let inRequirements = false;\n\n for (const line of lines) {\n const trimmed = line.trim();\n\n if (trimmed.match(/^##+\\s+Requirements?/i)) {\n inRequirements = true;\n continue;\n } else if (trimmed.match(/^##+/) && inRequirements) {\n break;\n }\n\n if (inRequirements && trimmed.startsWith('-')) {\n const requirement = trimmed.replace(/^-\\s*/, '').trim();\n if (requirement) {\n info.requirements.push(requirement);\n }\n }\n }\n\n return info;\n }\n\n /**\n * Convert to kebab-case\n */\n private toKebabCase(str: string): string {\n return str\n .replace(/([a-z])([A-Z])/g, '$1-$2')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '');\n }\n\n /**\n * Convert to PascalCase\n */\n private toPascalCase(str: string): string {\n return str\n .split(/[^a-zA-Z0-9]+/)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join('');\n }\n\n /**\n * Convert to snake_case\n */\n private toSnakeCase(str: string): string {\n return str\n .replace(/([a-z])([A-Z])/g, '$1_$2')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '_')\n .replace(/^_|_$/g, '');\n }\n}\n\n", "/**\n * HeraSpec Make Code Command\n * Generates code skeletons from specs\n */\nimport path from 'path';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { FileSystemUtils } from '../utils/file-system.js';\nimport { HERASPEC_DIR_NAME, SPECS_DIR_NAME, HERASPEC_MARKERS } from '../core/config.js';\nimport { MarkdownParser } from '../core/parsers/markdown-parser.js';\n\nexport class MakeCodeCommand {\n async execute(projectPath: string = '.', specName?: string): Promise<void> {\n const spinner = ora('Generating code from specs...').start();\n\n try {\n const resolvedPath = path.resolve(projectPath);\n const specsDir = path.join(resolvedPath, HERASPEC_DIR_NAME, SPECS_DIR_NAME);\n const projectMdPath = path.join(resolvedPath, HERASPEC_DIR_NAME, HERASPEC_MARKERS.PROJECT_MD);\n\n // Check if specs directory exists\n if (!(await FileSystemUtils.fileExists(specsDir))) {\n spinner.fail('Specs directory not found. Run \"heraspec init\" first.');\n process.exitCode = 1;\n return;\n }\n\n // Read project.md for context\n let projectInfo: { projectType?: string; stack?: string[] } = {};\n if (await FileSystemUtils.fileExists(projectMdPath)) {\n const projectContent = await FileSystemUtils.readFile(projectMdPath);\n projectInfo = this.extractProjectInfo(projectContent);\n }\n\n // Find spec files\n let specFiles: string[] = [];\n if (specName) {\n // Find specific spec\n const specPath = this.findSpecPath(specsDir, specName);\n if (specPath && (await FileSystemUtils.fileExists(specPath))) {\n specFiles = [specPath];\n } else {\n spinner.fail(`Spec \"${specName}\" not found`);\n process.exitCode = 1;\n return;\n }\n } else {\n // Find all specs\n specFiles = await this.findSpecFiles(specsDir);\n }\n\n if (specFiles.length === 0) {\n spinner.warn('No specs found. Create specs first using \"heraspec list --specs\".');\n return;\n }\n\n // Read and parse specs\n const specs = await this.readSpecs(specFiles);\n\n // Generate code files\n const generatedFiles = await this.generateCodeFiles(specs, resolvedPath, projectInfo);\n\n spinner.succeed(`Generated ${generatedFiles.length} code file(s)`);\n console.log(chalk.gray(`\\nSpecs analyzed: ${specFiles.length}`));\n generatedFiles.forEach((file: string) => {\n console.log(chalk.cyan(` \u2713 ${path.relative(resolvedPath, file)}`));\n });\n } catch (error) {\n spinner.fail(`Error: ${(error as Error).message}`);\n process.exitCode = 1;\n throw error;\n }\n }\n\n private extractProjectInfo(content: string): { projectType?: string; stack?: string[] } {\n const projectTypeMatch = content.match(/project[-\\s]type[s]?[:\\s]+([^\\n]+)/i);\n const stackMatch = content.match(/tech[-\\s]stack[:\\s]+([^\\n]+)/i);\n\n return {\n projectType: projectTypeMatch ? projectTypeMatch[1].trim().split(',')[0].trim() : undefined,\n stack: stackMatch ? stackMatch[1].split(',').map(s => s.trim()).filter(Boolean) : undefined,\n };\n }\n\n private findSpecPath(specsDir: string, specName: string): string | null {\n // Try direct path first\n const directPath = path.join(specsDir, `${specName}.md`);\n // Try nested path\n const nestedPath = path.join(specsDir, specName, 'spec.md');\n return directPath; // Return first option, caller will check existence\n }\n\n private async findSpecFiles(specsDir: string): Promise<string[]> {\n const specFiles: string[] = [];\n await this.findSpecFilesRecursive(specsDir, specFiles);\n return specFiles.sort();\n }\n\n private async findSpecFilesRecursive(dir: string, files: string[]): Promise<void> {\n const fs = await import('fs/promises');\n const entries = await fs.readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n await this.findSpecFilesRecursive(entryPath, files);\n } else if (entry.name.endsWith('.md') && entry.name !== 'README.md') {\n files.push(entryPath);\n }\n }\n }\n\n private async readSpecs(specFiles: string[]): Promise<Array<{ path: string; content: string; name: string; parsed: any }>> {\n const specs = [];\n\n for (const specFile of specFiles) {\n const content = await FileSystemUtils.readFile(specFile);\n const parser = new MarkdownParser(content);\n const specName = path.basename(specFile, '.md');\n\n try {\n const parsed = parser.parseSpec(specName);\n specs.push({\n path: specFile,\n content,\n name: parsed.name,\n parsed,\n });\n } catch (error) {\n console.warn(chalk.yellow(`Warning: Could not parse spec file ${specFile}. Skipping.`));\n }\n }\n\n return specs;\n }\n\n private async generateCodeFiles(\n specs: Array<{ path: string; content: string; name: string; parsed: any }>,\n projectPath: string,\n projectInfo: { projectType?: string; stack?: string[] }\n ): Promise<string[]> {\n const generatedFiles: string[] = [];\n const projectType = projectInfo.projectType || 'generic-webapp';\n\n for (const spec of specs) {\n const codeContent = this.generateCodeContent(spec, projectType, projectInfo);\n const outputPath = this.getOutputPath(projectPath, spec.name, projectType);\n \n // Ensure directory exists\n await FileSystemUtils.createDirectory(path.dirname(outputPath));\n await FileSystemUtils.writeFile(outputPath, codeContent);\n generatedFiles.push(outputPath);\n }\n\n return generatedFiles;\n }\n\n private getOutputPath(projectPath: string, specName: string, projectType: string): string {\n // Generate appropriate path based on project type\n const sanitizedName = specName.toLowerCase().replace(/[^a-z0-9-]/g, '-');\n \n if (projectType.includes('wordpress-plugin')) {\n return path.join(projectPath, 'includes', `class-${sanitizedName}.php`);\n } else if (projectType.includes('perfex-module')) {\n return path.join(projectPath, 'modules', sanitizedName, `${sanitizedName}.php`);\n } else if (projectType.includes('laravel')) {\n return path.join(projectPath, 'app', 'Services', `${this.toPascalCase(sanitizedName)}Service.php`);\n } else if (projectType.includes('node')) {\n return path.join(projectPath, 'src', 'services', `${sanitizedName}.js`);\n } else {\n // Generic\n return path.join(projectPath, 'src', `${sanitizedName}.ts`);\n }\n }\n\n private generateCodeContent(\n spec: { path: string; content: string; name: string; parsed: any },\n projectType: string,\n projectInfo: { projectType?: string; stack?: string[] }\n ): string {\n const lines: string[] = [];\n const className = this.toPascalCase(spec.name.replace(/[^a-zA-Z0-9]/g, ''));\n\n // Header comment\n lines.push(`/**`);\n lines.push(` * ${spec.name}`);\n lines.push(` * Generated from spec: ${path.basename(spec.path)}`);\n lines.push(` *`);\n lines.push(` * ${spec.parsed.overview || 'Generated code skeleton'}`);\n lines.push(` */`);\n lines.push('');\n\n if (projectType.includes('wordpress-plugin') || projectType.includes('perfex-module')) {\n // PHP class\n lines.push(`<?php`);\n lines.push('');\n lines.push(`class ${className} {`);\n lines.push('');\n \n // Add methods based on requirements\n spec.parsed.requirements.forEach((req: any) => {\n const methodName = this.toCamelCase(req.name.replace(/[^a-zA-Z0-9]/g, ''));\n lines.push(` /**`);\n lines.push(` * ${req.description || req.name}`);\n lines.push(` */`);\n lines.push(` public function ${methodName}() {`);\n lines.push(` // TODO: Implement ${req.name}`);\n lines.push(` }`);\n lines.push('');\n });\n \n lines.push('}');\n } else if (projectType.includes('laravel')) {\n // PHP Service class\n lines.push(`<?php`);\n lines.push('');\n lines.push(`namespace App\\\\Services;`);\n lines.push('');\n lines.push(`class ${className}Service {`);\n lines.push('');\n \n spec.parsed.requirements.forEach((req: any) => {\n const methodName = this.toCamelCase(req.name.replace(/[^a-zA-Z0-9]/g, ''));\n lines.push(` /**`);\n lines.push(` * ${req.description || req.name}`);\n lines.push(` */`);\n lines.push(` public function ${methodName}() {`);\n lines.push(` // TODO: Implement ${req.name}`);\n lines.push(` }`);\n lines.push('');\n });\n \n lines.push('}');\n } else if (projectType.includes('node')) {\n // JavaScript/TypeScript\n lines.push(`/**`);\n lines.push(` * ${spec.name} service`);\n lines.push(` */`);\n lines.push('');\n lines.push(`class ${className} {`);\n lines.push('');\n \n spec.parsed.requirements.forEach((req: any) => {\n const methodName = this.toCamelCase(req.name.replace(/[^a-zA-Z0-9]/g, ''));\n lines.push(` /**`);\n lines.push(` * ${req.description || req.name}`);\n lines.push(` */`);\n lines.push(` ${methodName}() {`);\n lines.push(` // TODO: Implement ${req.name}`);\n lines.push(` }`);\n lines.push('');\n });\n \n lines.push('}');\n lines.push('');\n lines.push(`module.exports = ${className};`);\n } else {\n // Generic TypeScript\n lines.push(`export class ${className} {`);\n lines.push('');\n \n spec.parsed.requirements.forEach((req: any) => {\n const methodName = this.toCamelCase(req.name.replace(/[^a-zA-Z0-9]/g, ''));\n lines.push(` /**`);\n lines.push(` * ${req.description || req.name}`);\n lines.push(` */`);\n lines.push(` ${methodName}(): void {`);\n lines.push(` // TODO: Implement ${req.name}`);\n lines.push(` }`);\n lines.push('');\n });\n \n lines.push('}');\n }\n\n lines.push('');\n lines.push(`// Generated by HeraSpec - Update this file based on implementation requirements`);\n\n return lines.join('\\n');\n }\n\n private toPascalCase(str: string): string {\n return str\n .replace(/[^a-zA-Z0-9]/g, ' ')\n .split(' ')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join('');\n }\n\n private toCamelCase(str: string): string {\n const pascal = this.toPascalCase(str);\n return pascal.charAt(0).toLowerCase() + pascal.slice(1);\n }\n}\n", "/**\n * HeraSpec Suggest Command\n * Analyzes project and suggests new features\n */\nimport path from 'path';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { FileSystemUtils } from '../utils/file-system.js';\nimport { HERASPEC_DIR_NAME, SPECS_DIR_NAME, HERASPEC_MARKERS } from '../core/config.js';\n\nexport class SuggestCommand {\n async execute(projectPath: string = '.'): Promise<void> {\n const spinner = ora('Analyzing project and generating suggestions...').start();\n\n try {\n const resolvedPath = path.resolve(projectPath);\n const specsDir = path.join(resolvedPath, HERASPEC_DIR_NAME, SPECS_DIR_NAME);\n const suggestionsDir = path.join(resolvedPath, HERASPEC_DIR_NAME, 'suggestions');\n const projectMdPath = path.join(resolvedPath, HERASPEC_DIR_NAME, HERASPEC_MARKERS.PROJECT_MD);\n\n // Check if specs directory exists\n if (!(await FileSystemUtils.fileExists(specsDir))) {\n spinner.fail('Specs directory not found. Run \"heraspec init\" first.');\n process.exitCode = 1;\n return;\n }\n\n // Ensure suggestions directory exists\n await FileSystemUtils.createDirectory(suggestionsDir);\n\n // Read project.md if exists\n let projectInfo: { name?: string; projectType?: string; stack?: string[] } = {};\n if (await FileSystemUtils.fileExists(projectMdPath)) {\n const projectContent = await FileSystemUtils.readFile(projectMdPath);\n projectInfo = this.extractProjectInfo(projectContent);\n }\n\n // Find all spec files\n const specFiles = await this.findSpecFiles(specsDir);\n\n // Read existing specs\n const specs = specFiles.length > 0 ? await this.readSpecs(specFiles) : [];\n\n // Generate suggestions\n const suggestions = this.generateSuggestions(specs, projectInfo);\n\n // Write suggestions file\n const suggestionsFilePath = path.join(suggestionsDir, 'feature-suggestions.md');\n const suggestionsContent = this.formatSuggestions(suggestions, projectInfo);\n await FileSystemUtils.writeFile(suggestionsFilePath, suggestionsContent);\n\n spinner.succeed(`Feature suggestions generated: ${suggestionsFilePath}`);\n console.log(chalk.gray(`\\nFound ${specs.length} existing feature(s)`));\n console.log(chalk.gray(`Generated ${suggestions.length} suggestion(s)`));\n } catch (error) {\n spinner.fail(`Error: ${(error as Error).message}`);\n process.exitCode = 1;\n throw error;\n }\n }\n\n /**\n * Extract project information from project.md\n */\n private extractProjectInfo(projectContent: string): { name?: string; projectType?: string; stack?: string[] } {\n const info: { name?: string; projectType?: string; stack?: string[] } = {};\n\n // Extract project name\n const nameMatch = projectContent.match(/^#\\s+(.+)$/m);\n if (nameMatch) {\n info.name = nameMatch[1].trim();\n }\n\n // Extract project type\n const projectTypeMatch = projectContent.match(/project[-\\s]type[s]?[:\\s]+([^\\n]+)/i);\n if (projectTypeMatch) {\n info.projectType = projectTypeMatch[1].trim();\n }\n\n // Extract tech stack\n const stackMatch = projectContent.match(/tech[-\\s]stack[:\\s]+([^\\n]+)/i);\n if (stackMatch) {\n info.stack = stackMatch[1]\n .split(',')\n .map(s => s.trim())\n .filter(s => s.length > 0);\n }\n\n return info;\n }\n\n /**\n * Find all spec files recursively\n */\n private async findSpecFiles(specsDir: string): Promise<string[]> {\n const specFiles: string[] = [];\n await this.findSpecFilesRecursive(specsDir, specFiles);\n return specFiles.sort();\n }\n\n /**\n * Recursively find spec files\n */\n private async findSpecFilesRecursive(dir: string, files: string[]): Promise<void> {\n const fs = await import('fs/promises');\n const entries = await fs.readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n await this.findSpecFilesRecursive(entryPath, files);\n } else if (entry.name.endsWith('.md')) {\n files.push(entryPath);\n }\n }\n }\n\n /**\n * Read all spec files\n */\n private async readSpecs(specFiles: string[]): Promise<Array<{ path: string; content: string; name: string }>> {\n const specs = [];\n\n for (const specFile of specFiles) {\n const content = await FileSystemUtils.readFile(specFile);\n const name = this.extractFeatureName(specFile, content);\n\n specs.push({\n path: specFile,\n content,\n name,\n });\n }\n\n return specs;\n }\n\n /**\n * Extract feature name from spec file\n */\n private extractFeatureName(filePath: string, content: string): string {\n const headingMatch = content.match(/^#+\\s+(.+)$/m);\n if (headingMatch) {\n return headingMatch[1].trim();\n }\n return path.basename(filePath, '.md');\n }\n\n /**\n * Generate feature suggestions based on existing specs\n */\n private generateSuggestions(\n specs: Array<{ path: string; content: string; name: string }>,\n projectInfo: { name?: string; projectType?: string; stack?: string[] }\n ): Array<{ title: string; description: string; category: string; integrationPoints: string[] }> {\n const suggestions: Array<{ title: string; description: string; category: string; integrationPoints: string[] }> = [];\n\n // Analyze existing features and suggest enhancements\n const existingFeatures = specs.map(s => s.name.toLowerCase());\n\n // Common suggestion patterns based on project type\n if (projectInfo.projectType?.toLowerCase().includes('plugin') || projectInfo.projectType?.toLowerCase().includes('module')) {\n if (!existingFeatures.some(f => f.includes('settings') || f.includes('config'))) {\n suggestions.push({\n title: 'Settings/Configuration Management',\n description: 'Add a centralized settings management feature to allow users to configure plugin/module behavior.',\n category: 'Configuration',\n integrationPoints: ['Admin interface', 'Database storage'],\n });\n }\n\n if (!existingFeatures.some(f => f.includes('report') || f.includes('analytics'))) {\n suggestions.push({\n title: 'Reporting and Analytics',\n description: 'Add reporting functionality to track usage, generate analytics, and provide insights.',\n category: 'Analytics',\n integrationPoints: ['Data collection', 'Dashboard'],\n });\n }\n }\n\n // General suggestions\n if (!existingFeatures.some(f => f.includes('export') || f.includes('import'))) {\n suggestions.push({\n title: 'Data Import/Export',\n description: 'Add functionality to import and export data in various formats (CSV, JSON, XML).',\n category: 'Data Management',\n integrationPoints: ['File handling', 'Data processing'],\n });\n }\n\n if (!existingFeatures.some(f => f.includes('search') || f.includes('filter'))) {\n suggestions.push({\n title: 'Advanced Search and Filtering',\n description: 'Implement advanced search and filtering capabilities to help users find information quickly.',\n category: 'User Experience',\n integrationPoints: ['Search interface', 'Data indexing'],\n });\n }\n\n if (!existingFeatures.some(f => f.includes('notification') || f.includes('alert'))) {\n suggestions.push({\n title: 'Notifications and Alerts',\n description: 'Add notification system to alert users about important events and updates.',\n category: 'Communication',\n integrationPoints: ['Event system', 'User preferences'],\n });\n }\n\n return suggestions;\n }\n\n /**\n * Format suggestions as markdown\n */\n private formatSuggestions(\n suggestions: Array<{ title: string; description: string; category: string; integrationPoints: string[] }>,\n projectInfo: { name?: string; projectType?: string; stack?: string[] }\n ): string {\n const lines: string[] = [];\n\n // Header\n lines.push('# Feature Suggestions');\n lines.push('');\n lines.push(`Generated for: ${projectInfo.name || 'Project'}`);\n lines.push(`Project Type: ${projectInfo.projectType || 'Not specified'}`);\n lines.push(`Generated on: ${new Date().toISOString()}`);\n lines.push('');\n lines.push('---');\n lines.push('');\n\n // Overview\n lines.push('## Overview');\n lines.push('');\n lines.push(`This document contains ${suggestions.length} feature suggestions that could enhance the project.`);\n lines.push('Each suggestion includes integration points and considerations for implementation.');\n lines.push('');\n lines.push('---');\n lines.push('');\n\n // Group by category\n const byCategory: Record<string, Array<{ title: string; description: string; category: string; integrationPoints: string[] }>> = {};\n suggestions.forEach(suggestion => {\n if (!byCategory[suggestion.category]) {\n byCategory[suggestion.category] = [];\n }\n byCategory[suggestion.category].push(suggestion);\n });\n\n // Write suggestions by category\n Object.entries(byCategory).forEach(([category, categorySuggestions]) => {\n lines.push(`## ${category}`);\n lines.push('');\n categorySuggestions.forEach((suggestion, index) => {\n lines.push(`### ${index + 1}. ${suggestion.title}`);\n lines.push('');\n lines.push(suggestion.description);\n lines.push('');\n if (suggestion.integrationPoints.length > 0) {\n lines.push('**Integration Points:**');\n lines.push('');\n suggestion.integrationPoints.forEach(point => {\n lines.push(`- ${point}`);\n });\n lines.push('');\n }\n if (index < categorySuggestions.length - 1) {\n lines.push('---');\n lines.push('');\n }\n });\n lines.push('');\n });\n\n // Footer\n lines.push('---');\n lines.push('');\n lines.push('*These suggestions are generated based on analysis of existing features and common patterns.*');\n lines.push('*Review and prioritize suggestions based on project requirements and goals.*');\n lines.push('');\n\n return lines.join('\\n');\n }\n}\n\n"],
5
- "mappings": ";AAGA,SAAS,eAAe;AACxB,SAAS,iBAAAA,sBAAqB;AAC9B,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,WAAAC,UAAS,QAAAC,aAAY;;;ACF9B,OAAO,SAAS;AAChB,OAAO,WAAW;AAClB,OAAOC,WAAU;;;ACHjB,SAAS,YAAY,UAAU;AAC/B,OAAO,UAAU;AAEV,IAAM,kBAAN,MAAsB;AAAA,EAC3B,aAAa,gBAAgB,SAAgC;AAC3D,UAAM,GAAG,MAAM,SAAS,EAAE,WAAW,KAAK,CAAC;AAAA,EAC7C;AAAA,EAEA,aAAa,WAAW,UAAoC;AAC1D,QAAI;AACF,YAAM,GAAG,OAAO,QAAQ;AACxB,aAAO;AAAA,IACT,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAAA,EAEA,aAAa,SAAS,UAAmC;AACvD,WAAO,MAAM,GAAG,SAAS,UAAU,OAAO;AAAA,EAC5C;AAAA,EAEA,aAAa,UAAU,UAAkB,SAAgC;AACvE,UAAM,GAAG,UAAU,UAAU,SAAS,OAAO;AAAA,EAC/C;AAAA,EAEA,aAAa,cAAc,SAAoC;AAC7D,WAAO,MAAM,GAAG,QAAQ,OAAO;AAAA,EACjC;AAAA,EAEA,aAAa,KAAK,UAAkB;AAClC,WAAO,MAAM,GAAG,KAAK,QAAQ;AAAA,EAC/B;AAAA,EAEA,aAAa,SAAS,KAAa,MAA6B;AAC9D,UAAM,GAAG,SAAS,KAAK,IAAI;AAAA,EAC7B;AAAA,EAEA,aAAa,cAAc,KAAa,MAA6B;AACnE,UAAM,GAAG,MAAM,MAAM,EAAE,WAAW,KAAK,CAAC;AACxC,UAAM,UAAU,MAAM,GAAG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AA,EAChB;AACF,CAAC;AAEH,SACG,QAAQ,QAAQ,EAChB,YAAY,qDAAqD,EACjE,OAAO,YAAY;AAClB,MAAI;AACF,UAAM,eAAe,IAAI,aAAa;AACtC,UAAM,aAAa,OAAO,GAAG;AAAA,EAC/B,SAAS,OAAO;AACd,YAAQ,MAAM,UAAW,MAAgB,OAAO,EAAE;AAClD,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;AAEH,SACG,QAAQ,kBAAkB,EAC1B,YAAY,4DAA4D,EACxE,OAAO,yBAAyB,kDAAkD,EAClF,OAAO,OAAO,WAAmB,YAAuC;AACvE,MAAI;AACF,UAAM,eAAe,IAAI,aAAa;AACtC,UAAM,aAAa,IAAI,WAAW,SAAS,aAAa,GAAG;AAAA,EAC7D,SAAS,OAAO;AACd,YAAQ,MAAM,UAAW,MAAgB,OAAO,EAAE;AAClD,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;AAEH,SACG,QAAQ,qBAAqB,EAC7B,YAAY,kEAAkE,EAC9E,OAAO,yBAAyB,kDAAkD,EAClF,OAAO,OAAO,WAAmB,YAAuC;AACvE,MAAI;AACF,UAAM,eAAe,IAAI,aAAa;AACtC,UAAM,aAAa,OAAO,WAAW,SAAS,aAAa,GAAG;AAAA,EAChE,SAAS,OAAO;AACd,YAAQ,MAAM,UAAW,MAAgB,OAAO,EAAE;AAClD,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;AAEH,QAAQ,MAAM;",
6
- "names": ["createRequire", "fileURLToPath", "dirname", "join", "path", "path", "path", "path", "path", "ora", "chalk", "path", "ora", "chalk", "path", "ora", "chalk", "path", "ora", "chalk", "path", "chalk", "readFileSync", "path", "path", "path", "readFileSync", "path", "chalk", "path", "chalk", "readFileSync", "path", "z", "z", "z", "readFileSync", "path", "path", "chalk", "path", "ora", "require", "packageJsonPath", "path", "ora", "chalk", "path", "chalk", "ora", "ora", "path", "chalk", "fs", "path", "chalk", "ora", "ora", "path", "chalk", "fs", "path", "chalk", "ora", "ora", "path", "chalk", "fs", "path", "chalk", "ora", "ora", "path", "chalk", "fs", "require", "createRequire", "__filename", "fileURLToPath", "__dirname", "dirname", "join"]
3
+ "sources": ["../src/utils/file-system.ts", "../src/core/config.ts", "../src/core/templates/skills-template-map.ts", "../src/core/memory/memory-schema.ts", "../src/core/memory/memory-types.ts", "../src/core/memory/memory-store.ts", "../src/core/memory/memory-search.ts", "../src/core/memory/memory-vector.ts", "../src/core/memory/context-config.ts", "../src/core/memory/context-generator.ts", "../src/core/memory/config-advisor.ts", "../src/commands/memory.ts", "../src/core/skills/skill-parser.ts", "../src/core/skills/skill-manager.ts", "../src/core/skills/index.ts", "../src/commands/skill.ts", "../src/cli/index.ts", "../src/core/init.ts", "../src/core/templates/index.ts", "../src/core/list.ts", "../src/core/archive.ts", "../src/core/parsers/markdown-parser.ts", "../src/core/sync.ts", "../src/core/restore.ts", "../src/commands/show.ts", "../src/utils/task-parser.ts", "../src/commands/validate.ts", "../src/core/validation/validator.ts", "../src/core/schemas/base.schema.ts", "../src/core/schemas/spec.schema.ts", "../src/core/schemas/change.schema.ts", "../src/commands/helper.ts", "../src/commands/make-docs.ts", "../src/commands/make-test.ts", "../src/commands/make-code.ts", "../src/commands/suggest.ts", "../src/commands/hotfix.ts", "../src/commands/explore.ts", "../src/core/parsers/code-parser.ts"],
4
+ "sourcesContent": ["/**\r\n * File system utilities for HeraSpec\r\n */\r\nimport { promises as fs } from 'fs';\r\nimport path from 'path';\r\n\r\nexport class FileSystemUtils {\r\n static async createDirectory(dirPath: string): Promise<void> {\r\n await fs.mkdir(dirPath, { recursive: true });\r\n }\r\n\r\n static async fileExists(filePath: string): Promise<boolean> {\r\n try {\r\n await fs.access(filePath);\r\n return true;\r\n } catch {\r\n return false;\r\n }\r\n }\r\n\r\n static async readFile(filePath: string): Promise<string> {\r\n return await fs.readFile(filePath, 'utf-8');\r\n }\r\n\r\n static async writeFile(filePath: string, content: string): Promise<void> {\r\n await fs.writeFile(filePath, content, 'utf-8');\r\n }\r\n\r\n static async readDirectory(dirPath: string): Promise<string[]> {\r\n return await fs.readdir(dirPath);\r\n }\r\n\r\n static async stat(filePath: string) {\r\n return await fs.stat(filePath);\r\n }\r\n\r\n static async copyFile(src: string, dest: string): Promise<void> {\r\n await fs.copyFile(src, dest);\r\n }\r\n\r\n static async copyDirectory(src: string, dest: string): Promise<void> {\r\n await fs.mkdir(dest, { recursive: true });\r\n const entries = await fs.readdir(src, { withFileTypes: true });\r\n\r\n for (const entry of entries) {\r\n const srcPath = path.join(src, entry.name);\r\n const destPath = path.join(dest, entry.name);\r\n\r\n if (entry.isDirectory()) {\r\n await this.copyDirectory(srcPath, destPath);\r\n } else {\r\n await fs.copyFile(srcPath, destPath);\r\n }\r\n }\r\n }\r\n\r\n static async removeFile(filePath: string): Promise<void> {\r\n await fs.unlink(filePath);\r\n }\r\n\r\n static async removeDirectory(dirPath: string, recursive = true): Promise<void> {\r\n // Use fs.rm for Node.js 14.14.0+ (fs.rmdir with recursive is deprecated)\r\n // Fallback to fs.rmdir for older versions\r\n if (typeof (fs as any).rm === 'function') {\r\n await (fs as any).rm(dirPath, { recursive, force: true });\r\n } else {\r\n await fs.rmdir(dirPath, { recursive });\r\n }\r\n }\r\n\r\n static async moveFile(src: string, dest: string): Promise<void> {\r\n await fs.rename(src, dest);\r\n }\r\n\r\n static joinPath(...segments: string[]): string {\r\n return path.join(...segments);\r\n }\r\n\r\n static resolvePath(...segments: string[]): string {\r\n return path.resolve(...segments);\r\n }\r\n\r\n static getDirectoryName(filePath: string): string {\r\n return path.dirname(filePath);\r\n }\r\n\r\n static getBaseName(filePath: string): string {\r\n return path.basename(filePath);\r\n }\r\n\r\n static async generateTree(\r\n dirPath: string,\r\n maxDepth: number = 3,\r\n ignoreDirs: string[] = ['node_modules', '.git', 'dist', 'build', 'vendor', '.next', '.nuxt', 'heraspec', '.heraspec'],\r\n currentDepth: number = 0,\r\n prefix: string = ''\r\n ): Promise<string> {\r\n if (currentDepth >= maxDepth) return '';\r\n\r\n let result = '';\r\n let entries: string[];\r\n try {\r\n entries = await fs.readdir(dirPath);\r\n } catch {\r\n return result;\r\n }\r\n\r\n const validEntries = [];\r\n for (const entry of entries) {\r\n if (ignoreDirs.includes(entry)) continue;\r\n // Skip hidden folders to keep tree clean\r\n if (entry.startsWith('.')) {\r\n const stat = await this.stat(path.join(dirPath, entry)).catch(() => null);\r\n if (stat?.isDirectory()) continue;\r\n }\r\n validEntries.push(entry);\r\n }\r\n\r\n // Sort: directories first, then files\r\n const statsCache = new Map<string, any>();\r\n for (const entry of validEntries) {\r\n const stat = await this.stat(path.join(dirPath, entry)).catch(() => null);\r\n statsCache.set(entry, stat);\r\n }\r\n\r\n validEntries.sort((a, b) => {\r\n const statA = statsCache.get(a);\r\n const statB = statsCache.get(b);\r\n if (statA?.isDirectory() && !statB?.isDirectory()) return -1;\r\n if (!statA?.isDirectory() && statB?.isDirectory()) return 1;\r\n return a.localeCompare(b);\r\n });\r\n\r\n for (let i = 0; i < validEntries.length; i++) {\r\n const entry = validEntries[i];\r\n const isLast = i === validEntries.length - 1;\r\n const marker = isLast ? '\u2514\u2500\u2500 ' : '\u251C\u2500\u2500 ';\r\n const childPrefix = prefix + (isLast ? ' ' : '\u2502 ');\r\n\r\n const entryPath = path.join(dirPath, entry);\r\n const stat = statsCache.get(entry);\r\n\r\n if (stat?.isDirectory()) {\r\n result += `${prefix}${marker}${entry}/\\n`;\r\n result += await this.generateTree(entryPath, maxDepth, ignoreDirs, currentDepth + 1, childPrefix);\r\n } else {\r\n result += `${prefix}${marker}${entry}\\n`;\r\n }\r\n }\r\n\r\n return result;\r\n }\r\n}\r\n", "/**\r\n * HeraSpec Core Configuration\r\n */\r\n\r\nexport const HERASPEC_DIR_NAME = 'heraspec';\r\nexport const SPECS_DIR_NAME = 'specs';\r\nexport const CHANGES_DIR_NAME = 'changes';\r\nexport const ARCHIVES_DIR_NAME = 'archives';\r\nexport const SKILLS_DIR_NAME = 'skills';\r\nexport const KNOWLEDGE_DIR_NAME = 'knowledge';\r\nexport const MEMORY_DIR_NAME = 'memory';\r\n\r\nexport const PROJECT_TYPES = [\r\n 'wordpress-plugin',\r\n 'wordpress-theme',\r\n 'perfex-module',\r\n 'laravel-package',\r\n 'node-service',\r\n 'generic-webapp',\r\n 'backend-api',\r\n 'frontend-app',\r\n 'multi-stack',\r\n] as const;\r\n\r\nexport type ProjectType = (typeof PROJECT_TYPES)[number];\r\n\r\nexport const SKILLS: Record<ProjectType, string[]> = {\r\n 'wordpress-plugin': [\r\n 'admin-settings-page',\r\n 'custom-post-type',\r\n 'shortcode',\r\n 'rest-endpoint',\r\n 'ajax-handler',\r\n 'activation-hook',\r\n 'deactivation-hook',\r\n 'admin-menu-item',\r\n 'meta-box',\r\n 'taxonomy',\r\n 'plugin-check',\r\n 'plugin-directory',\r\n ],\r\n 'wordpress-theme': [\r\n 'theme-setup',\r\n 'custom-post-type',\r\n 'template-part',\r\n 'widget-area',\r\n 'customizer-setting',\r\n 'theme-option',\r\n ],\r\n 'perfex-module': [\r\n 'module-codebase',\r\n 'module-registration',\r\n 'permission-group',\r\n 'admin-menu-item',\r\n 'login-hook',\r\n 'database-table',\r\n 'api-endpoint',\r\n ],\r\n 'laravel-package': [\r\n 'service-provider',\r\n 'config-file',\r\n 'artisan-command',\r\n 'migration',\r\n 'model',\r\n 'controller',\r\n 'middleware',\r\n 'route',\r\n ],\r\n 'node-service': [\r\n 'express-route',\r\n 'middleware',\r\n 'database-model',\r\n 'service-layer',\r\n 'api-endpoint',\r\n 'background-job',\r\n ],\r\n 'generic-webapp': [\r\n 'page',\r\n 'component',\r\n 'api-endpoint',\r\n 'database-table',\r\n 'authentication',\r\n 'authorization',\r\n ],\r\n 'backend-api': [\r\n 'endpoint',\r\n 'middleware',\r\n 'authentication',\r\n 'authorization',\r\n 'database-model',\r\n 'validation',\r\n ],\r\n 'frontend-app': [\r\n 'page',\r\n 'component',\r\n 'route',\r\n 'store',\r\n 'service',\r\n 'hook',\r\n ],\r\n 'multi-stack': [\r\n 'cross-platform-feature',\r\n 'api-contract',\r\n 'shared-type',\r\n 'integration-point',\r\n ],\r\n} as const;\r\n\r\nexport type Skill = typeof SKILLS[ProjectType][number];\r\n\r\nexport interface HeraSpecConfig {\r\n projectType?: ProjectType | ProjectType[];\r\n domains?: string[];\r\n stack?: string[];\r\n}\r\n\r\nexport interface SpecMeta {\r\n projectType?: ProjectType | ProjectType[];\r\n domain?: string;\r\n stack?: string | string[];\r\n}\r\n\r\nexport const HERASPEC_MARKERS = {\r\n PROJECT_MD: 'project.md',\r\n AGENTS_MD: 'AGENTS.heraspec.md',\r\n CONFIG_YAML: 'config.yaml',\r\n PROPOSAL_MD: 'proposal.md',\r\n TASKS_MD: 'tasks.md',\r\n DESIGN_MD: 'design.md',\r\n} as const;\r\n\r\n", "/**\r\n * Skills Template Mapping\r\n * Maps skill names to their template files and resources\r\n */\r\nexport interface SkillTemplateInfo {\r\n templateFileName: string; // Just the filename, path resolved at runtime\r\n isCrossCutting: boolean;\r\n projectType?: string;\r\n resourceDirs?: string[]; // Additional directories to copy (e.g., scripts, templates, data)\r\n viFileName?: string; // Vietnamese translation file (e.g., skill.vi.md)\r\n}\r\n\r\n/**\r\n * Mapping of skill names to their template information\r\n * Key format: \"projectType:skillName\" for project-specific, or \"skillName\" for cross-cutting\r\n */\r\nexport const SKILL_TEMPLATE_MAP: Record<string, SkillTemplateInfo> = {\r\n // Cross-cutting skills\r\n 'ui-ux': {\r\n templateFileName: 'ui-ux-skill.md',\r\n isCrossCutting: true,\r\n resourceDirs: ['scripts', 'templates', 'data'],\r\n },\r\n 'design-system': {\r\n templateFileName: 'design-system-skill.md',\r\n isCrossCutting: true,\r\n resourceDirs: ['scripts', 'data', 'knowledge/design-systems'],\r\n },\r\n 'documents': {\r\n templateFileName: 'documents-skill.md',\r\n isCrossCutting: true,\r\n resourceDirs: ['documents/templates'],\r\n },\r\n 'content-optimization': {\r\n templateFileName: 'content-optimization-skill.md',\r\n isCrossCutting: true,\r\n },\r\n 'unit-test': {\r\n templateFileName: 'unit-test-skill.md',\r\n isCrossCutting: true,\r\n },\r\n 'integration-test': {\r\n templateFileName: 'integration-test-skill.md',\r\n isCrossCutting: true,\r\n },\r\n 'e2e-test': {\r\n templateFileName: 'e2e-test-skill.md',\r\n isCrossCutting: true,\r\n },\r\n 'suggestion': {\r\n templateFileName: 'suggestion-skill.md',\r\n isCrossCutting: true,\r\n },\r\n 'sourcecode-analyzer': {\r\n templateFileName: 'sourcecode-analyzer-skill.md',\r\n isCrossCutting: true,\r\n viFileName: 'sourcecode-analyzer-skill.vi.md',\r\n },\r\n 'project-memory': {\r\n templateFileName: 'project-memory-skill.md',\r\n viFileName: 'project-memory-skill.vi.md',\r\n isCrossCutting: true,\r\n },\r\n 'smart-explore': {\r\n templateFileName: 'smart-explore-skill.md',\r\n isCrossCutting: true,\r\n },\r\n 'deploy-documentation': {\r\n templateFileName: 'deploy-documentation-skill.md',\r\n isCrossCutting: true,\r\n resourceDirs: ['templates'],\r\n },\r\n \r\n // Perfex module skills\r\n 'perfex-module:module-codebase': {\r\n templateFileName: 'module-codebase-skill.md',\r\n isCrossCutting: false,\r\n projectType: 'perfex-module',\r\n },\r\n 'wordpress:ux-element': {\r\n templateFileName: 'ux-element-skill.md',\r\n isCrossCutting: false,\r\n projectType: 'wordpress',\r\n resourceDirs: ['ux-element/templates'],\r\n },\r\n 'wordpress:plugin-standard': {\r\n templateFileName: 'wordpress-plugin-standard-skill.md',\r\n isCrossCutting: false,\r\n projectType: 'wordpress',\r\n resourceDirs: ['wordpress-plugin-standard/templates'],\r\n },\r\n 'wordpress:plugin-check': {\r\n templateFileName: 'wordpress-plugin-check-skill.md',\r\n isCrossCutting: false,\r\n projectType: 'wordpress',\r\n },\r\n 'wordpress:plugin-directory': {\r\n templateFileName: 'plugin-directory-skill.md',\r\n isCrossCutting: false,\r\n projectType: 'wordpress',\r\n },\r\n // WordPress Plugin specific (matches PROJECT_TYPES)\r\n 'wordpress-plugin:plugin-check': {\r\n templateFileName: 'wordpress-plugin-check-skill.md',\r\n isCrossCutting: false,\r\n projectType: 'wordpress-plugin',\r\n },\r\n 'wordpress-plugin:plugin-directory': {\r\n templateFileName: 'plugin-directory-skill.md',\r\n isCrossCutting: false,\r\n projectType: 'wordpress-plugin',\r\n },\r\n};\r\n\r\n/**\r\n * Get template info for a skill\r\n */\r\nexport function getSkillTemplateInfo(skillName: string, projectType?: string): SkillTemplateInfo | null {\r\n // Try project-specific first\r\n if (projectType) {\r\n const key = `${projectType}:${skillName}`;\r\n if (SKILL_TEMPLATE_MAP[key]) {\r\n return SKILL_TEMPLATE_MAP[key];\r\n }\r\n }\r\n \r\n // Try cross-cutting\r\n if (SKILL_TEMPLATE_MAP[skillName]) {\r\n return SKILL_TEMPLATE_MAP[skillName];\r\n }\r\n \r\n // If we haven't found it and no projectType was specified, assume inferred lookup\r\n if (!projectType) {\r\n for (const key of Object.keys(SKILL_TEMPLATE_MAP)) {\r\n // Check if key is \"projectType:skillName\"\r\n const parts = key.split(':');\r\n if (parts.length === 2 && parts[1] === skillName) {\r\n return SKILL_TEMPLATE_MAP[key];\r\n }\r\n }\r\n }\r\n \r\n return null;\r\n}\r\n\r\n/**\r\n * Get all available skill templates\r\n */\r\nexport function getAllSkillTemplates(): Array<{ skillName: string; projectType?: string; info: SkillTemplateInfo }> {\r\n const result: Array<{ skillName: string; projectType?: string; info: SkillTemplateInfo }> = [];\r\n \r\n for (const [key, info] of Object.entries(SKILL_TEMPLATE_MAP)) {\r\n if (info.isCrossCutting) {\r\n result.push({ skillName: key, info });\r\n } else {\r\n const [projectType, skillName] = key.split(':');\r\n result.push({ skillName, projectType, info });\r\n }\r\n }\r\n \r\n return result;\r\n}\r\n\r\n", "/**\n * HeraSpec Memory Schema\n * SQLite schema definitions, FTS5 indexes, and migration system\n */\n\nexport const SCHEMA_VERSION = 3;\n\n/**\n * Core table definitions\n */\nexport const CREATE_TABLES = `\n -- Sessions tracking\n CREATE TABLE IF NOT EXISTS sessions (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL UNIQUE,\n project TEXT NOT NULL,\n started_at TEXT NOT NULL DEFAULT (datetime('now')),\n started_at_epoch INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000),\n completed_at TEXT,\n completed_at_epoch INTEGER,\n status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active', 'completed'))\n );\n\n -- Observation records\n CREATE TABLE IF NOT EXISTS observations (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL DEFAULT '',\n project TEXT NOT NULL DEFAULT '',\n type TEXT NOT NULL DEFAULT 'change' CHECK(type IN ('decision', 'bugfix', 'feature', 'refactor', 'discovery', 'change')),\n title TEXT NOT NULL DEFAULT '',\n narrative TEXT DEFAULT '',\n concepts TEXT DEFAULT '[]',\n files_read TEXT DEFAULT '[]',\n files_modified TEXT DEFAULT '[]',\n discovery_tokens INTEGER DEFAULT 0,\n embedding TEXT,\n created_at TEXT NOT NULL DEFAULT (datetime('now')),\n created_at_epoch INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)\n );\n\n -- Session summaries\n CREATE TABLE IF NOT EXISTS session_summaries (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL DEFAULT '',\n project TEXT NOT NULL DEFAULT '',\n request TEXT DEFAULT '',\n investigated TEXT DEFAULT '',\n learned TEXT DEFAULT '',\n completed TEXT DEFAULT '',\n next_steps TEXT DEFAULT '',\n files_read TEXT DEFAULT '[]',\n files_edited TEXT DEFAULT '[]',\n created_at TEXT NOT NULL DEFAULT (datetime('now')),\n created_at_epoch INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)\n );\n\n -- Database size history tracking\n CREATE TABLE IF NOT EXISTS db_history (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n project TEXT NOT NULL,\n db_size_bytes INTEGER NOT NULL,\n created_at TEXT NOT NULL DEFAULT (datetime('now')),\n created_at_epoch INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)\n );\n`;\n\n/**\n * Index definitions for query optimization\n */\nexport const CREATE_INDEXES = `\n CREATE INDEX IF NOT EXISTS idx_obs_project ON observations(project);\n CREATE INDEX IF NOT EXISTS idx_obs_type ON observations(type);\n CREATE INDEX IF NOT EXISTS idx_obs_created ON observations(created_at_epoch DESC);\n CREATE INDEX IF NOT EXISTS idx_obs_session ON observations(session_id);\n CREATE INDEX IF NOT EXISTS idx_sum_project ON session_summaries(project);\n CREATE INDEX IF NOT EXISTS idx_sum_created ON session_summaries(created_at_epoch DESC);\n CREATE INDEX IF NOT EXISTS idx_sessions_project ON sessions(project);\n CREATE INDEX IF NOT EXISTS idx_sessions_status ON sessions(status);\n CREATE INDEX IF NOT EXISTS idx_history_project ON db_history(project);\n`;\n\n/**\n * FTS5 virtual tables for full-text search\n */\nexport const CREATE_FTS5 = `\n CREATE VIRTUAL TABLE IF NOT EXISTS observations_fts USING fts5(\n title,\n narrative,\n concepts,\n content='observations',\n content_rowid='id',\n tokenize='porter unicode61'\n );\n\n CREATE VIRTUAL TABLE IF NOT EXISTS summaries_fts USING fts5(\n request,\n learned,\n completed,\n content='session_summaries',\n content_rowid='id',\n tokenize='porter unicode61'\n );\n`;\n\n/**\n * FTS5 sync triggers - keep FTS index in sync with main tables\n */\nexport const CREATE_FTS_TRIGGERS = `\n -- Observations FTS triggers\n CREATE TRIGGER IF NOT EXISTS observations_ai AFTER INSERT ON observations BEGIN\n INSERT INTO observations_fts(rowid, title, narrative, concepts)\n VALUES (new.id, new.title, new.narrative, new.concepts);\n END;\n\n CREATE TRIGGER IF NOT EXISTS observations_ad AFTER DELETE ON observations BEGIN\n INSERT INTO observations_fts(observations_fts, rowid, title, narrative, concepts)\n VALUES ('delete', old.id, old.title, old.narrative, old.concepts);\n END;\n\n CREATE TRIGGER IF NOT EXISTS observations_au AFTER UPDATE ON observations BEGIN\n INSERT INTO observations_fts(observations_fts, rowid, title, narrative, concepts)\n VALUES ('delete', old.id, old.title, old.narrative, old.concepts);\n INSERT INTO observations_fts(rowid, title, narrative, concepts)\n VALUES (new.id, new.title, new.narrative, new.concepts);\n END;\n\n -- Summaries FTS triggers\n CREATE TRIGGER IF NOT EXISTS summaries_ai AFTER INSERT ON session_summaries BEGIN\n INSERT INTO summaries_fts(rowid, request, learned, completed)\n VALUES (new.id, new.request, new.learned, new.completed);\n END;\n\n CREATE TRIGGER IF NOT EXISTS summaries_ad AFTER DELETE ON session_summaries BEGIN\n INSERT INTO summaries_fts(summaries_fts, rowid, request, learned, completed)\n VALUES ('delete', old.id, old.request, old.learned, old.completed);\n END;\n\n CREATE TRIGGER IF NOT EXISTS summaries_au AFTER UPDATE ON session_summaries BEGIN\n INSERT INTO summaries_fts(summaries_fts, rowid, request, learned, completed)\n VALUES ('delete', old.id, old.request, old.learned, old.completed);\n INSERT INTO summaries_fts(rowid, request, learned, completed)\n VALUES (new.id, new.request, new.learned, new.completed);\n END;\n`;\n\n/**\n * Initialize database with schema\n */\nexport function initializeSchema(db: any): void {\n // Enable WAL mode for better concurrent performance\n db.pragma('journal_mode = WAL');\n db.pragma('foreign_keys = ON');\n\n // Create tables\n db.exec(CREATE_TABLES);\n\n // Create indexes\n db.exec(CREATE_INDEXES);\n\n // Create FTS5 tables\n db.exec(CREATE_FTS5);\n\n // Create FTS sync triggers\n db.exec(CREATE_FTS_TRIGGERS);\n\n // Set schema version\n db.pragma(`user_version = ${SCHEMA_VERSION}`);\n}\n\n/**\n * Check if migration is needed\n */\nexport function needsMigration(db: any): boolean {\n const currentVersion = db.pragma('user_version', { simple: true }) as number;\n return currentVersion < SCHEMA_VERSION;\n}\n\n/**\n * Run migrations from current version to latest\n */\nexport function runMigrations(db: any): void {\n const currentVersion = db.pragma('user_version', { simple: true }) as number;\n\n if (currentVersion === 0) {\n // Fresh database - initialize from scratch\n initializeSchema(db);\n return;\n }\n\n // Future migrations go here:\n if (currentVersion < 2) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS db_history (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n project TEXT NOT NULL,\n db_size_bytes INTEGER NOT NULL,\n created_at TEXT NOT NULL DEFAULT (datetime('now')),\n created_at_epoch INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)\n );\n CREATE INDEX IF NOT EXISTS idx_history_project ON db_history(project);\n `);\n }\n\n if (currentVersion < 3) {\n // Check if column exists before adding to prevent errors if manually added\n const columnExists = db.prepare(\"PRAGMA table_info(observations)\").all().some((col: any) => col.name === 'embedding');\n if (!columnExists) {\n db.exec(`ALTER TABLE observations ADD COLUMN embedding TEXT;`);\n }\n }\n\n db.pragma(`user_version = ${SCHEMA_VERSION}`);\n}\n", "/**\n * HeraSpec Memory Types\n * Interfaces and types for the project memory system\n */\n\n// ============ Observation Types ============\n\nexport const OBSERVATION_TYPES = [\n 'decision',\n 'bugfix',\n 'feature',\n 'refactor',\n 'discovery',\n 'change',\n] as const;\n\nexport type ObservationType = (typeof OBSERVATION_TYPES)[number];\n\nexport interface Observation {\n id: number;\n sessionId: string;\n project: string;\n type: ObservationType;\n title: string;\n narrative: string;\n concepts: string[]; // Tags for categorization\n filesRead: string[]; // Files read during this observation\n filesModified: string[]; // Files modified during this observation\n discoveryTokens: number;\n embedding?: number[]; // Vector embedding // Estimated tokens spent discovering this\n createdAt: string; // ISO 8601 timestamp\n createdAtEpoch: number; // Unix timestamp in milliseconds\n}\n\nexport interface ObservationInput {\n sessionId?: string;\n project?: string;\n type: ObservationType;\n title: string;\n narrative?: string;\n concepts?: string[];\n filesRead?: string[];\n filesModified?: string[];\n discoveryTokens?: number;\n embedding?: number[];\n}\n\n// ============ Session Summary Types ============\n\nexport interface SessionSummary {\n id: number;\n sessionId: string;\n project: string;\n request: string; // What the user asked for\n investigated: string; // What was investigated/researched\n learned: string; // What was learned\n completed: string; // What was completed\n nextSteps: string; // What remains to be done\n filesRead: string[];\n filesEdited: string[];\n createdAt: string;\n createdAtEpoch: number;\n}\n\nexport interface SessionSummaryInput {\n sessionId?: string;\n project?: string;\n request: string;\n investigated?: string;\n learned?: string;\n completed?: string;\n nextSteps?: string;\n filesRead?: string[];\n filesEdited?: string[];\n}\n\n// ============ Session Types ============\n\nexport interface Session {\n id: number;\n sessionId: string;\n project: string;\n startedAt: string;\n startedAtEpoch: number;\n completedAt: string | null;\n completedAtEpoch: number | null;\n status: 'active' | 'completed';\n}\n\n// ============ Search Types ============\n\nexport interface MemorySearchResult {\n id: number;\n type: ObservationType;\n title: string;\n narrative: string;\n concepts: string[];\n filesModified: string[];\n createdAt: string;\n createdAtEpoch: number;\n rank?: number; // FTS5 relevance score\n estimatedTokens: number; // Estimated tokens for this result\n}\n\nexport interface SummarySearchResult {\n id: number;\n sessionId: string;\n request: string;\n completed: string;\n learned: string;\n createdAt: string;\n createdAtEpoch: number;\n rank?: number;\n estimatedTokens: number;\n}\n\nexport interface SearchOptions {\n query?: string;\n type?: ObservationType | ObservationType[];\n concepts?: string[];\n files?: string[];\n dateStart?: string; // ISO date or epoch\n dateEnd?: string;\n project?: string;\n limit?: number;\n offset?: number;\n orderBy?: 'relevance' | 'date_desc' | 'date_asc';\n}\n\nexport interface TimelineItem {\n type: 'observation' | 'summary';\n id: number;\n title: string;\n timestamp: string;\n epoch: number;\n icon: string;\n estimatedTokens: number;\n}\n\n// ============ Context Types ============\n\nexport interface ContextConfig {\n totalObservationCount: number; // Total observations to include in context\n fullObservationCount: number; // How many show full narrative\n sessionCount: number; // How many session summaries to include\n observationTypes: Set<string>; // Filter by types\n observationConcepts: Set<string>; // Filter by concepts\n maxTokens: number; // Token budget\n showLastSummary: boolean;\n}\n\nexport interface MemoryStatus {\n observationCount: number;\n summaryCount: number;\n sessionCount: number;\n oldestObservation: string | null;\n newestObservation: string | null;\n topConcepts: Array<{ concept: string; count: number }>;\n topFiles: Array<{ file: string; count: number }>;\n estimatedTotalTokens: number;\n dbSizeBytes: number;\n}\n\n// ============ Analytics Types ============\n\nexport interface DbHistoryRecord {\n id: number;\n project: string;\n dbSizeBytes: number;\n createdAt: string;\n createdAtEpoch: number;\n}\n\nexport interface ProjectAnalytics {\n project: string;\n totalOps: number;\n tokensWithMemory: number;\n tokensWithoutMemory: number;\n savingsTokens: number;\n savingsPercent: number;\n dbSizeBytes: number;\n history?: DbHistoryRecord[];\n}\n\n// ============ Utility Constants ============\n\nexport const OBSERVATION_TYPE_ICONS: Record<ObservationType, string> = {\n decision: '\u2696\uFE0F',\n bugfix: '\uD83D\uDD34',\n feature: '\uD83D\uDFE2',\n refactor: '\uD83D\uDD04',\n discovery: '\uD83D\uDD35',\n change: '\u2705',\n};\n\nexport const CHARS_PER_TOKEN_ESTIMATE = 4;\n\nexport function estimateTokens(text: string | null | undefined): number {\n if (!text) return 0;\n return Math.ceil(text.length / CHARS_PER_TOKEN_ESTIMATE);\n}\n", "/**\n * HeraSpec Memory Store\n * SQLite-based CRUD operations for observations and session summaries\n */\nimport path from 'path';\nimport { HERASPEC_DIR_NAME, MEMORY_DIR_NAME } from '../config.js';\nimport { initializeSchema, needsMigration, runMigrations } from './memory-schema.js';\nimport type {\n Observation,\n ObservationInput,\n SessionSummary,\n SessionSummaryInput,\n Session,\n MemoryStatus,\n ObservationType,\n ProjectAnalytics,\n} from './memory-types.js';\nimport { estimateTokens } from './memory-types.js';\n\nconst DB_FILENAME = 'heraspec-memory.db';\n\nexport class MemoryStore {\n private db: any;\n private dbPath: string;\n private hasChanges = false;\n\n constructor(projectPath: string = '.') {\n this.dbPath = path.join(projectPath, HERASPEC_DIR_NAME, MEMORY_DIR_NAME, DB_FILENAME);\n this.db = null;\n }\n\n /**\n * Open database connection, init schema if needed\n */\n open(): void {\n if (this.db) return;\n\n // Dynamic import better-sqlite3 (native module)\n let Database: any;\n try {\n Database = require('better-sqlite3');\n } catch {\n throw new Error(\n 'better-sqlite3 is required for HeraSpec memory. Install it with: npm install better-sqlite3'\n );\n }\n\n // Ensure directory exists\n const dir = path.dirname(this.dbPath);\n const fs = require('fs');\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n this.db = new Database(this.dbPath);\n\n // Initialize or migrate schema\n if (needsMigration(this.db)) {\n runMigrations(this.db);\n }\n }\n\n /**\n * Close database connection\n */\n close(): void {\n if (this.db) {\n if (this.hasChanges) {\n this.logDbSizeChange();\n this.hasChanges = false;\n }\n this.db.close();\n this.db = null;\n }\n }\n\n private logDbSizeChange(): void {\n try {\n const project = this.detectProjectName();\n const fs = require('fs');\n if (fs.existsSync(this.dbPath)) {\n // Also account for WAL file if it exists, since it contains unflushed data\n let totalSize = fs.statSync(this.dbPath).size;\n const walPath = this.dbPath + '-wal';\n if (fs.existsSync(walPath)) {\n totalSize += fs.statSync(walPath).size;\n }\n\n const now = new Date();\n this.db.prepare(`\n INSERT INTO db_history (project, db_size_bytes, created_at, created_at_epoch)\n VALUES (?, ?, ?, ?)\n `).run(project, totalSize, now.toISOString(), now.getTime());\n }\n } catch (e) {\n // fail silently\n }\n }\n\n /**\n * Get the raw database reference (for advanced queries)\n */\n getDb(): any {\n this.ensureOpen();\n return this.db;\n }\n\n private ensureOpen(): void {\n if (!this.db) {\n this.open();\n }\n }\n\n // ============ Observations ============\n\n /**\n * Add a new observation\n */\n addObservation(input: ObservationInput): Observation {\n this.ensureOpen();\n\n const now = new Date();\n const sessionId = input.sessionId || this.generateSessionId();\n const project = input.project || this.detectProjectName();\n\n const stmt = this.db.prepare(`\n INSERT INTO observations (session_id, project, type, title, narrative, concepts, files_read, files_modified, discovery_tokens, embedding, created_at, created_at_epoch)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n\n const result = stmt.run(\n sessionId,\n project,\n input.type,\n input.title,\n input.narrative || '',\n JSON.stringify(input.concepts || []),\n JSON.stringify(input.filesRead || []),\n JSON.stringify(input.filesModified || []),\n input.discoveryTokens || 0,\n input.embedding ? JSON.stringify(input.embedding) : null,\n now.toISOString(),\n now.getTime()\n );\n\n this.hasChanges = true;\n\n return this.getObservationById(result.lastInsertRowid as number)!;\n }\n\n /**\n * Get observation by ID\n */\n getObservationById(id: number): Observation | null {\n this.ensureOpen();\n\n const row = this.db.prepare('SELECT * FROM observations WHERE id = ?').get(id);\n return row ? this.rowToObservation(row) : null;\n }\n\n /**\n * Get observations by IDs (batch)\n */\n getObservationsByIds(ids: number[]): Observation[] {\n this.ensureOpen();\n if (ids.length === 0) return [];\n\n const placeholders = ids.map(() => '?').join(',');\n const rows = this.db\n .prepare(`SELECT * FROM observations WHERE id IN (${placeholders}) ORDER BY created_at_epoch DESC`)\n .all(...ids);\n\n return rows.map((row: any) => this.rowToObservation(row));\n }\n\n /**\n * Get recent observations for a project\n */\n getRecentObservations(project?: string, limit: number = 50): Observation[] {\n this.ensureOpen();\n\n let sql = 'SELECT * FROM observations';\n const params: any[] = [];\n\n if (project) {\n sql += ' WHERE project = ?';\n params.push(project);\n }\n\n sql += ' ORDER BY created_at_epoch DESC LIMIT ?';\n params.push(limit);\n\n const rows = this.db.prepare(sql).all(...params);\n return rows.map((row: any) => this.rowToObservation(row));\n }\n\n /**\n * Delete observations older than N days\n */\n pruneObservations(daysOld: number, project?: string): number {\n this.ensureOpen();\n\n const cutoffEpoch = Date.now() - daysOld * 24 * 60 * 60 * 1000;\n let sql = 'DELETE FROM observations WHERE created_at_epoch < ?';\n const params: any[] = [cutoffEpoch];\n\n if (project) {\n sql += ' AND project = ?';\n params.push(project);\n }\n\n const result = this.db.prepare(sql).run(...params);\n if (result.changes > 0) this.hasChanges = true;\n return result.changes;\n }\n\n // ============ Session Summaries ============\n\n /**\n * Add a new session summary\n */\n addSummary(input: SessionSummaryInput): SessionSummary {\n this.ensureOpen();\n\n const now = new Date();\n const sessionId = input.sessionId || this.generateSessionId();\n const project = input.project || this.detectProjectName();\n\n const stmt = this.db.prepare(`\n INSERT INTO session_summaries (session_id, project, request, investigated, learned, completed, next_steps, files_read, files_edited, created_at, created_at_epoch)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n\n const result = stmt.run(\n sessionId,\n project,\n input.request,\n input.investigated || '',\n input.learned || '',\n input.completed || '',\n input.nextSteps || '',\n JSON.stringify(input.filesRead || []),\n JSON.stringify(input.filesEdited || []),\n now.toISOString(),\n now.getTime()\n );\n\n this.hasChanges = true;\n\n return this.getSummaryById(result.lastInsertRowid as number)!;\n }\n\n /**\n * Get summary by ID\n */\n getSummaryById(id: number): SessionSummary | null {\n this.ensureOpen();\n\n const row = this.db.prepare('SELECT * FROM session_summaries WHERE id = ?').get(id);\n return row ? this.rowToSummary(row) : null;\n }\n\n /**\n * Get recent summaries for a project\n */\n getRecentSummaries(project?: string, limit: number = 20): SessionSummary[] {\n this.ensureOpen();\n\n let sql = 'SELECT * FROM session_summaries';\n const params: any[] = [];\n\n if (project) {\n sql += ' WHERE project = ?';\n params.push(project);\n }\n\n sql += ' ORDER BY created_at_epoch DESC LIMIT ?';\n params.push(limit);\n\n const rows = this.db.prepare(sql).all(...params);\n return rows.map((row: any) => this.rowToSummary(row));\n }\n\n // ============ Status ============\n\n /**\n * Get memory status statistics\n */\n getStatus(project?: string): MemoryStatus {\n this.ensureOpen();\n\n const projectFilter = project ? ' WHERE project = ?' : '';\n const params = project ? [project] : [];\n\n const obsCount = this.db\n .prepare(`SELECT COUNT(*) as count FROM observations${projectFilter}`)\n .get(...params)?.count || 0;\n\n const sumCount = this.db\n .prepare(`SELECT COUNT(*) as count FROM session_summaries${projectFilter}`)\n .get(...params)?.count || 0;\n\n const sessCount = this.db\n .prepare(`SELECT COUNT(*) as count FROM sessions${projectFilter}`)\n .get(...params)?.count || 0;\n\n const oldest = this.db\n .prepare(`SELECT created_at FROM observations${projectFilter} ORDER BY created_at_epoch ASC LIMIT 1`)\n .get(...params);\n\n const newest = this.db\n .prepare(`SELECT created_at FROM observations${projectFilter} ORDER BY created_at_epoch DESC LIMIT 1`)\n .get(...params);\n\n // Top concepts\n const allObs = this.db\n .prepare(`SELECT concepts FROM observations${projectFilter}`)\n .all(...params);\n\n const conceptCounts: Record<string, number> = {};\n for (const row of allObs) {\n try {\n const concepts = JSON.parse(row.concepts || '[]');\n for (const c of concepts) {\n conceptCounts[c] = (conceptCounts[c] || 0) + 1;\n }\n } catch { /* skip malformed */ }\n }\n\n const topConcepts = Object.entries(conceptCounts)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 10)\n .map(([concept, count]) => ({ concept, count }));\n\n // Top files\n const fileCounts: Record<string, number> = {};\n for (const row of allObs) {\n try {\n const files = JSON.parse(row.files_modified || '[]');\n for (const f of files) {\n fileCounts[f] = (fileCounts[f] || 0) + 1;\n }\n } catch { /* skip malformed */ }\n }\n\n const topFiles = Object.entries(fileCounts)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 10)\n .map(([file, count]) => ({ file, count }));\n\n // Estimate total tokens\n const allNarratives = this.db\n .prepare(`SELECT narrative FROM observations${projectFilter}`)\n .all(...params);\n let totalTokens = 0;\n for (const row of allNarratives) {\n totalTokens += estimateTokens(row.narrative);\n }\n\n // DB file size\n let dbSizeBytes = 0;\n try {\n const fs = require('fs');\n const stats = fs.statSync(this.dbPath);\n dbSizeBytes = stats.size;\n } catch { /* file might not exist yet */ }\n\n return {\n observationCount: obsCount,\n summaryCount: sumCount,\n sessionCount: sessCount,\n oldestObservation: oldest?.created_at || null,\n newestObservation: newest?.created_at || null,\n topConcepts,\n topFiles,\n estimatedTotalTokens: totalTokens,\n dbSizeBytes,\n };\n }\n\n // ============ Analytics ============\n\n /**\n * Get token saving statistics for all known projects in memory\n */\n getAnalytics(): ProjectAnalytics[] {\n this.ensureOpen();\n \n // Default factor: Cost applied per context read if memory wasn't used ~ 50,000 tokens\n const TOKENS_WITHOUT_MEMORY_PER_OP = 50000;\n // Default factor: Cost of context generation if memory IS used ~ 3,000 tokens\n const CONTEXT_GENERATION_OVERHEAD = 3000; \n\n const obsQuery = this.db.prepare(`\n SELECT \n project, \n COUNT(*) as obs_count, \n SUM(discovery_tokens) as total_discovery,\n SUM(length(narrative)) as total_chars\n FROM observations \n GROUP BY project\n `).all();\n\n const sumQuery = this.db.prepare(`\n SELECT \n project, \n COUNT(*) as sum_count,\n SUM(length(learned) + length(completed)) as total_chars\n FROM session_summaries \n GROUP BY project\n `).all();\n\n const projectData = new Map<string, any>();\n\n for (const row of obsQuery) {\n if (!row.project) continue;\n projectData.set(row.project, {\n ops: row.obs_count,\n discovery: row.total_discovery || 0,\n textChars: row.total_chars || 0\n });\n }\n\n for (const row of sumQuery) {\n if (!row.project) continue;\n const data = projectData.get(row.project) || { ops: 0, discovery: 0, textChars: 0 };\n data.ops += row.sum_count;\n data.textChars += (row.total_chars || 0);\n projectData.set(row.project, data);\n }\n\n const results: ProjectAnalytics[] = [];\n\n for (const [project, data] of projectData.entries()) {\n // Tokens with memory: Actual discovery tokens used + narrative estimate if discovery=0 + context generation overhead\n const contentTokens = data.discovery > 0 ? data.discovery : Math.ceil(data.textChars / 4);\n let tokensWithMemory = contentTokens + (data.ops * CONTEXT_GENERATION_OVERHEAD);\n\n // Tokens without memory: Imagine re-reading codebase blindly (50k context per session/action)\n let tokensWithoutMemory = data.ops * TOKENS_WITHOUT_MEMORY_PER_OP;\n\n // Ensure it's not negative or weird\n if (tokensWithoutMemory < tokensWithMemory) {\n tokensWithoutMemory = tokensWithMemory; // Failsafe\n }\n\n let savingsTokens = tokensWithoutMemory - tokensWithMemory;\n let savingsPercent = tokensWithoutMemory > 0 ? (savingsTokens / tokensWithoutMemory) * 100 : 0;\n\n let dbSizeBytes = 0;\n try {\n const fs = require('fs');\n if (fs.existsSync(this.dbPath)) {\n dbSizeBytes = fs.statSync(this.dbPath).size;\n const walPath = this.dbPath + '-wal';\n if (fs.existsSync(walPath)) {\n dbSizeBytes += fs.statSync(walPath).size;\n }\n }\n } catch { /* ignore */ }\n\n results.push({\n project,\n totalOps: data.ops,\n tokensWithMemory,\n tokensWithoutMemory,\n savingsTokens,\n savingsPercent,\n dbSizeBytes\n });\n }\n\n // Sort by savings highest to lowest\n return results.sort((a, b) => b.savingsTokens - a.savingsTokens);\n }\n\n /**\n * Get database size history updates\n */\n getDbHistory(project: string, limit: number = 13): DbHistoryRecord[] {\n this.ensureOpen();\n const rows = this.db.prepare(`\n SELECT * FROM db_history \n WHERE project = ? \n ORDER BY created_at_epoch DESC \n LIMIT ?\n `).all(project, limit);\n\n return rows.map((row: any) => ({\n id: row.id,\n project: row.project,\n dbSizeBytes: row.db_size_bytes,\n createdAt: row.created_at,\n createdAtEpoch: row.created_at_epoch\n }));\n }\n\n // ============ Helpers ============\n\n private rowToObservation(row: any): Observation {\n return {\n id: row.id,\n sessionId: row.session_id,\n project: row.project,\n type: row.type as ObservationType,\n title: row.title,\n narrative: row.narrative || '',\n concepts: this.parseJsonArray(row.concepts),\n filesRead: this.parseJsonArray(row.files_read),\n filesModified: this.parseJsonArray(row.files_modified),\n discoveryTokens: row.discovery_tokens || 0,\n embedding: row.embedding ? JSON.parse(row.embedding) : undefined,\n createdAt: row.created_at,\n createdAtEpoch: row.created_at_epoch,\n };\n }\n\n private rowToSummary(row: any): SessionSummary {\n return {\n id: row.id,\n sessionId: row.session_id,\n project: row.project,\n request: row.request || '',\n investigated: row.investigated || '',\n learned: row.learned || '',\n completed: row.completed || '',\n nextSteps: row.next_steps || '',\n filesRead: this.parseJsonArray(row.files_read),\n filesEdited: this.parseJsonArray(row.files_edited),\n createdAt: row.created_at,\n createdAtEpoch: row.created_at_epoch,\n };\n }\n\n private parseJsonArray(json: string | null): string[] {\n if (!json) return [];\n try {\n const parsed = JSON.parse(json);\n return Array.isArray(parsed) ? parsed : [];\n } catch {\n return [];\n }\n }\n\n private generateSessionId(): string {\n const now = new Date();\n const random = Math.random().toString(36).substring(2, 8);\n return `${now.toISOString().replace(/[:.]/g, '-')}-${random}`;\n }\n\n private detectProjectName(): string {\n try {\n const fs = require('fs');\n const pkgPath = path.join(process.cwd(), 'package.json');\n if (fs.existsSync(pkgPath)) {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));\n return pkg.name || path.basename(process.cwd());\n }\n } catch { /* ignore */ }\n return path.basename(process.cwd());\n }\n}\n", "/**\n * HeraSpec Memory Search\n * FTS5-based full-text search with progressive disclosure\n */\nimport type {\n MemorySearchResult,\n SummarySearchResult,\n SearchOptions,\n TimelineItem,\n ObservationType,\n} from './memory-types.js';\nimport { OBSERVATION_TYPE_ICONS, estimateTokens } from './memory-types.js';\nimport { MemoryStore } from './memory-store.js';\n\nexport class MemorySearch {\n private store: MemoryStore;\n\n constructor(store: MemoryStore) {\n this.store = store;\n }\n\n /**\n * Search observations using FTS5 full-text search\n * Returns compact index results (Layer 1 of progressive disclosure)\n */\n searchObservations(options: SearchOptions): MemorySearchResult[] {\n const db = this.store.getDb();\n const params: any[] = [];\n let sql: string;\n\n if (options.query) {\n // FTS5 MATCH query with bm25 ranking\n sql = `\n SELECT o.*, bm25(observations_fts) as rank\n FROM observations o\n JOIN observations_fts fts ON o.id = fts.rowid\n WHERE observations_fts MATCH ?\n `;\n params.push(this.sanitizeFtsQuery(options.query));\n } else {\n sql = 'SELECT *, 0 as rank FROM observations WHERE 1=1';\n }\n\n // Apply filters\n if (options.project) {\n sql += ' AND o.project = ?';\n params.push(options.project);\n }\n\n if (options.type) {\n const types = Array.isArray(options.type) ? options.type : [options.type];\n const placeholders = types.map(() => '?').join(',');\n sql += ` AND o.type IN (${placeholders})`;\n params.push(...types);\n }\n\n if (options.concepts && options.concepts.length > 0) {\n // Search concepts JSON array for any matching concept\n const conceptConditions = options.concepts\n .map(() => `o.concepts LIKE ?`)\n .join(' OR ');\n sql += ` AND (${conceptConditions})`;\n params.push(...options.concepts.map(c => `%\"${c}\"%`));\n }\n\n if (options.files && options.files.length > 0) {\n const fileConditions = options.files\n .map(() => `(o.files_modified LIKE ? OR o.files_read LIKE ?)`)\n .join(' OR ');\n sql += ` AND (${fileConditions})`;\n for (const f of options.files) {\n params.push(`%${f}%`, `%${f}%`);\n }\n }\n\n if (options.dateStart) {\n const epoch = this.parseDate(options.dateStart);\n if (epoch) {\n sql += ' AND o.created_at_epoch >= ?';\n params.push(epoch);\n }\n }\n\n if (options.dateEnd) {\n const epoch = this.parseDate(options.dateEnd);\n if (epoch) {\n sql += ' AND o.created_at_epoch <= ?';\n params.push(epoch);\n }\n }\n\n // Order\n if (options.query) {\n sql += ' ORDER BY rank'; // FTS5 bm25 - lower is better\n } else if (options.orderBy === 'date_asc') {\n sql += ' ORDER BY o.created_at_epoch ASC';\n } else {\n sql += ' ORDER BY o.created_at_epoch DESC';\n }\n\n // Limit & offset\n sql += ' LIMIT ?';\n params.push(options.limit || 20);\n\n if (options.offset) {\n sql += ' OFFSET ?';\n params.push(options.offset);\n }\n\n const rows = db.prepare(sql).all(...params);\n\n return rows.map((row: any) => ({\n id: row.id,\n type: row.type as ObservationType,\n title: row.title,\n narrative: row.narrative || '',\n concepts: this.parseJsonSafe(row.concepts),\n filesModified: this.parseJsonSafe(row.files_modified),\n createdAt: row.created_at,\n createdAtEpoch: row.created_at_epoch,\n rank: row.rank,\n estimatedTokens: estimateTokens(row.narrative),\n }));\n }\n\n /**\n * Search session summaries using FTS5\n */\n searchSummaries(options: SearchOptions): SummarySearchResult[] {\n const db = this.store.getDb();\n const params: any[] = [];\n let sql: string;\n\n if (options.query) {\n sql = `\n SELECT s.*, bm25(summaries_fts) as rank\n FROM session_summaries s\n JOIN summaries_fts fts ON s.id = fts.rowid\n WHERE summaries_fts MATCH ?\n `;\n params.push(this.sanitizeFtsQuery(options.query));\n } else {\n sql = 'SELECT *, 0 as rank FROM session_summaries WHERE 1=1';\n }\n\n if (options.project) {\n sql += ' AND s.project = ?';\n params.push(options.project);\n }\n\n if (options.dateStart) {\n const epoch = this.parseDate(options.dateStart);\n if (epoch) {\n sql += ' AND s.created_at_epoch >= ?';\n params.push(epoch);\n }\n }\n\n if (options.dateEnd) {\n const epoch = this.parseDate(options.dateEnd);\n if (epoch) {\n sql += ' AND s.created_at_epoch <= ?';\n params.push(epoch);\n }\n }\n\n if (options.query) {\n sql += ' ORDER BY rank';\n } else {\n sql += ' ORDER BY s.created_at_epoch DESC';\n }\n\n sql += ' LIMIT ?';\n params.push(options.limit || 10);\n\n const rows = db.prepare(sql).all(...params);\n\n return rows.map((row: any) => ({\n id: row.id,\n sessionId: row.session_id,\n request: row.request || '',\n completed: row.completed || '',\n learned: row.learned || '',\n createdAt: row.created_at,\n createdAtEpoch: row.created_at_epoch,\n rank: row.rank,\n estimatedTokens: estimateTokens(row.request) + estimateTokens(row.completed) + estimateTokens(row.learned),\n }));\n }\n\n /**\n * Get timeline of observations around a specific point\n */\n getTimeline(options: {\n anchorId?: number;\n anchorEpoch?: number;\n depthBefore?: number;\n depthAfter?: number;\n project?: string;\n }): TimelineItem[] {\n const db = this.store.getDb();\n const depthBefore = options.depthBefore ?? 5;\n const depthAfter = options.depthAfter ?? 5;\n const items: TimelineItem[] = [];\n const params: any[] = [];\n\n let anchorEpoch = options.anchorEpoch;\n\n // If anchorId provided, find its epoch\n if (options.anchorId && !anchorEpoch) {\n const obs = db.prepare('SELECT created_at_epoch FROM observations WHERE id = ?').get(options.anchorId);\n if (obs) anchorEpoch = obs.created_at_epoch;\n }\n\n if (!anchorEpoch) {\n // Default: latest\n anchorEpoch = Date.now();\n }\n\n // Get observations before anchor\n let sqlBefore = `SELECT * FROM observations WHERE created_at_epoch <= ?`;\n params.length = 0;\n params.push(anchorEpoch);\n\n if (options.project) {\n sqlBefore += ' AND project = ?';\n params.push(options.project);\n }\n\n sqlBefore += ` ORDER BY created_at_epoch DESC LIMIT ?`;\n params.push(depthBefore + 1);\n\n const beforeRows = db.prepare(sqlBefore).all(...params);\n\n // Get observations after anchor\n params.length = 0;\n let sqlAfter = `SELECT * FROM observations WHERE created_at_epoch > ?`;\n params.push(anchorEpoch);\n\n if (options.project) {\n sqlAfter += ' AND project = ?';\n params.push(options.project);\n }\n\n sqlAfter += ` ORDER BY created_at_epoch ASC LIMIT ?`;\n params.push(depthAfter);\n\n const afterRows = db.prepare(sqlAfter).all(...params);\n\n // Combine\n const allRows = [...beforeRows.reverse(), ...afterRows];\n\n for (const row of allRows) {\n items.push({\n type: 'observation',\n id: row.id,\n title: row.title,\n timestamp: row.created_at,\n epoch: row.created_at_epoch,\n icon: OBSERVATION_TYPE_ICONS[row.type as ObservationType] || '\uD83D\uDCCC',\n estimatedTokens: estimateTokens(row.narrative),\n });\n }\n\n // Also get summaries in the time range\n if (allRows.length > 0) {\n const minEpoch = allRows[0].created_at_epoch;\n const maxEpoch = allRows[allRows.length - 1].created_at_epoch;\n\n params.length = 0;\n let sqlSum = `SELECT * FROM session_summaries WHERE created_at_epoch >= ? AND created_at_epoch <= ?`;\n params.push(minEpoch, maxEpoch);\n\n if (options.project) {\n sqlSum += ' AND project = ?';\n params.push(options.project);\n }\n\n const sumRows = db.prepare(sqlSum).all(...params);\n\n for (const row of sumRows) {\n items.push({\n type: 'summary',\n id: row.id,\n title: `Session: ${row.request || 'Untitled'}`,\n timestamp: row.created_at,\n epoch: row.created_at_epoch,\n icon: '\uD83C\uDFAF',\n estimatedTokens: estimateTokens(row.request) + estimateTokens(row.completed),\n });\n }\n }\n\n // Sort chronologically\n items.sort((a, b) => a.epoch - b.epoch);\n\n return items;\n }\n\n /**\n * Format search results as markdown (compact index view)\n */\n formatResultsAsIndex(results: MemorySearchResult[], query?: string): string {\n if (results.length === 0) {\n return query ? `No results found matching \"${query}\"` : 'No observations found.';\n }\n\n const lines: string[] = [];\n lines.push(`Found ${results.length} observation(s)${query ? ` matching \"${query}\"` : ''}:\\n`);\n lines.push('| ID | Time | Type | Title | Tokens |');\n lines.push('|----|------|------|-------|--------|');\n\n for (const r of results) {\n const time = this.formatTime(r.createdAtEpoch);\n const icon = OBSERVATION_TYPE_ICONS[r.type] || '\uD83D\uDCCC';\n lines.push(`| #${r.id} | ${time} | ${icon} | ${r.title} | ~${r.estimatedTokens} |`);\n }\n\n lines.push('');\n lines.push('Use `heraspec memory search --id <ID>` to see full details.');\n\n return lines.join('\\n');\n }\n\n /**\n * Format timeline as markdown\n */\n formatTimeline(items: TimelineItem[]): string {\n if (items.length === 0) return 'No timeline data found.';\n\n const lines: string[] = [];\n lines.push(`# Timeline (${items.length} items)\\n`);\n\n // Group by day\n const byDay = new Map<string, TimelineItem[]>();\n for (const item of items) {\n const day = new Date(item.epoch).toLocaleDateString('en-US', {\n year: 'numeric', month: 'short', day: 'numeric',\n });\n if (!byDay.has(day)) byDay.set(day, []);\n byDay.get(day)!.push(item);\n }\n\n for (const [day, dayItems] of byDay) {\n lines.push(`### ${day}\\n`);\n lines.push('| ID | Time | Type | Title | Tokens |');\n lines.push('|----|------|------|-------|--------|');\n\n for (const item of dayItems) {\n const time = this.formatTime(item.epoch);\n lines.push(`| #${item.id} | ${time} | ${item.icon} | ${item.title} | ~${item.estimatedTokens} |`);\n }\n lines.push('');\n }\n\n return lines.join('\\n');\n }\n\n // ============ Helpers ============\n\n /**\n * Sanitize FTS5 query - escape special characters\n */\n private sanitizeFtsQuery(query: string): string {\n // Remove FTS5 special operators that could cause syntax errors\n // Keep simple words for matching\n return query\n .replace(/[*\"(){}[\\]^~:]/g, ' ')\n .replace(/\\b(AND|OR|NOT|NEAR)\\b/gi, '')\n .trim()\n .split(/\\s+/)\n .filter(w => w.length > 0)\n .map(w => `\"${w}\"`)\n .join(' OR ');\n }\n\n private parseJsonSafe(json: string | null): string[] {\n if (!json) return [];\n try {\n const parsed = JSON.parse(json);\n return Array.isArray(parsed) ? parsed : [];\n } catch {\n return [];\n }\n }\n\n private parseDate(input: string): number | null {\n // Try epoch\n const num = Number(input);\n if (!isNaN(num) && num > 1e12) return num; // Already epoch ms\n if (!isNaN(num) && num > 1e9) return num * 1000; // Epoch seconds\n\n // Try ISO date\n const d = new Date(input);\n return isNaN(d.getTime()) ? null : d.getTime();\n }\n\n private formatTime(epoch: number): string {\n return new Date(epoch).toLocaleTimeString('en-US', {\n hour: '2-digit', minute: '2-digit', hour12: true,\n });\n }\n}\n", "/**\n * HeraSpec Memory Vector Search\n * Handles embedding generation and cosine similarity search using @xenova/transformers\n */\nimport { pipeline } from '@xenova/transformers';\nimport type { Observation, MemorySearchResult } from './memory-types.js';\nimport { OBSERVATION_TYPE_ICONS, estimateTokens } from './memory-types.js';\n\nexport class MemoryVector {\n private static extractor: any = null;\n\n /**\n * Initialize the embedding model.\n * This downloads the model on first run (cached in node_modules or system cache).\n */\n static async initModel() {\n if (!this.extractor) {\n // Use a lightweight, fast embedding model suitable for CLI\n this.extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');\n }\n return this.extractor;\n }\n\n /**\n * Generate an embedding vector for a given text.\n */\n static async generateEmbedding(text: string): Promise<number[]> {\n try {\n const extractor = await this.initModel();\n // Generate sentence embeddings\n const output = await extractor(text, { pooling: 'mean', normalize: true });\n // The output is a Tensor. We convert it to a standard JS array.\n return Array.from(output.data);\n } catch (error) {\n // console.warn('Failed to generate embedding:', error);\n return [];\n }\n }\n\n /**\n * Calculate Cosine Similarity between two vectors.\n * Returns a value between -1 and 1. Higher is more similar.\n */\n static cosineSimilarity(vecA: number[], vecB: number[]): number {\n if (!vecA || !vecB || vecA.length === 0 || vecA.length !== vecB.length) {\n return 0;\n }\n\n let dotProduct = 0;\n let normA = 0;\n let normB = 0;\n\n for (let i = 0; i < vecA.length; i++) {\n dotProduct += vecA[i] * vecB[i];\n normA += vecA[i] * vecA[i];\n normB += vecB[i] * vecB[i];\n }\n\n if (normA === 0 || normB === 0) return 0;\n return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));\n }\n\n /**\n * Search through observations using semantic vector search.\n */\n static async search(query: string, observations: Observation[], limit: number = 10): Promise<MemorySearchResult[]> {\n if (observations.length === 0) return [];\n\n const queryEmbedding = await this.generateEmbedding(query);\n if (queryEmbedding.length === 0) {\n return []; // Fallback to FTS if embedding fails? Handled by caller.\n }\n\n const results: Array<{ obs: Observation; score: number }> = [];\n\n // Calculate similarity for each observation\n for (const obs of observations) {\n // Only rank observations that have an embedding\n if (obs.embedding && obs.embedding.length > 0) {\n const score = this.cosineSimilarity(queryEmbedding, obs.embedding);\n results.push({ obs, score });\n }\n }\n\n // Sort by descending score\n results.sort((a, b) => b.score - a.score);\n\n // Format as MemorySearchResult\n return results.slice(0, limit).map(({ obs, score }) => {\n return {\n id: obs.id,\n type: obs.type,\n title: obs.title,\n narrative: obs.narrative,\n concepts: obs.concepts || [],\n filesModified: obs.filesModified || [],\n createdAt: obs.createdAt,\n createdAtEpoch: obs.createdAtEpoch,\n rank: score, // Use score as rank for sorting/display\n estimatedTokens: estimateTokens(obs.narrative)\n };\n });\n }\n}\n", "/**\n * HeraSpec Context Config\n * Configuration for context generation with defaults\n */\nimport path from 'path';\nimport { HERASPEC_DIR_NAME, MEMORY_DIR_NAME } from '../config.js';\nimport type { ContextConfig } from './memory-types.js';\n\nconst CONFIG_FILENAME = 'config.json';\n\n/**\n * Default context configuration\n */\nexport const DEFAULT_CONTEXT_CONFIG: ContextConfig = {\n totalObservationCount: 50,\n fullObservationCount: 5,\n sessionCount: 5,\n observationTypes: new Set(['decision', 'bugfix', 'feature', 'refactor', 'discovery', 'change']),\n observationConcepts: new Set(), // Empty = all concepts\n maxTokens: 6000,\n showLastSummary: true,\n};\n\n/**\n * Load context configuration from file or return defaults\n */\nexport function loadContextConfig(projectPath: string = '.'): ContextConfig {\n const configPath = path.join(projectPath, HERASPEC_DIR_NAME, MEMORY_DIR_NAME, CONFIG_FILENAME);\n\n try {\n const fs = require('fs');\n if (!fs.existsSync(configPath)) {\n return { ...DEFAULT_CONTEXT_CONFIG };\n }\n\n const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));\n return mergeConfig(raw);\n } catch {\n return { ...DEFAULT_CONTEXT_CONFIG };\n }\n}\n\n/**\n * Save context configuration to file\n */\nexport function saveContextConfig(config: ContextConfig, projectPath: string = '.'): void {\n const configDir = path.join(projectPath, HERASPEC_DIR_NAME, MEMORY_DIR_NAME);\n const configPath = path.join(configDir, CONFIG_FILENAME);\n\n const fs = require('fs');\n if (!fs.existsSync(configDir)) {\n fs.mkdirSync(configDir, { recursive: true });\n }\n\n const serializable = {\n totalObservationCount: config.totalObservationCount,\n fullObservationCount: config.fullObservationCount,\n sessionCount: config.sessionCount,\n observationTypes: Array.from(config.observationTypes),\n observationConcepts: Array.from(config.observationConcepts),\n maxTokens: config.maxTokens,\n showLastSummary: config.showLastSummary,\n };\n\n fs.writeFileSync(configPath, JSON.stringify(serializable, null, 2), 'utf-8');\n}\n\n/**\n * Merge user config with defaults\n */\nfunction mergeConfig(raw: any): ContextConfig {\n const defaults = DEFAULT_CONTEXT_CONFIG;\n\n return {\n totalObservationCount: raw.totalObservationCount ?? defaults.totalObservationCount,\n fullObservationCount: raw.fullObservationCount ?? defaults.fullObservationCount,\n sessionCount: raw.sessionCount ?? defaults.sessionCount,\n observationTypes: raw.observationTypes\n ? new Set(raw.observationTypes)\n : new Set(defaults.observationTypes),\n observationConcepts: raw.observationConcepts\n ? new Set(raw.observationConcepts)\n : new Set(defaults.observationConcepts),\n maxTokens: raw.maxTokens ?? defaults.maxTokens,\n showLastSummary: raw.showLastSummary ?? defaults.showLastSummary,\n };\n}\n", "/**\n * HeraSpec Context Generator\n * Generates context markdown for AI agent sessions (complementary approach)\n */\nimport { MemoryStore } from './memory-store.js';\nimport { MemorySearch } from './memory-search.js';\nimport { loadContextConfig } from './context-config.js';\nimport { OBSERVATION_TYPE_ICONS, estimateTokens } from './memory-types.js';\nimport type { Observation, SessionSummary, ContextConfig, ObservationType } from './memory-types.js';\n\nexport class ContextGenerator {\n private store: MemoryStore;\n private search: MemorySearch;\n\n constructor(projectPath: string = '.') {\n this.store = new MemoryStore(projectPath);\n this.search = new MemorySearch(this.store);\n }\n\n /**\n * Generate context markdown for AI agent consumption\n * Writes to heraspec/memory/context.md for on-demand reading\n */\n generateContext(projectPath: string = '.'): string {\n const config = loadContextConfig(projectPath);\n\n this.store.open();\n try {\n const observations = this.store.getRecentObservations(undefined, config.totalObservationCount);\n const summaries = this.store.getRecentSummaries(undefined, config.sessionCount);\n\n if (observations.length === 0 && summaries.length === 0) {\n return this.renderEmptyState();\n }\n\n let architectureObs: Observation | null = null;\n try {\n const db = (this.store as any).getDb();\n const row = db.prepare(`SELECT id FROM observations WHERE type = 'discovery' AND concepts LIKE '%\"architecture\"%' ORDER BY created_at_epoch DESC LIMIT 1`).get();\n if (row) {\n architectureObs = this.store.getObservationById(row.id);\n }\n } catch (e) { }\n\n // Filter out ALL architecture observations from recent activity to avoid clutter\n // if the user ran 'heraspec memory index' multiple times.\n const filteredObservations = observations.filter(o => \n !(o.type === 'discovery' && o.concepts.includes('architecture'))\n );\n\n return this.buildContextOutput(filteredObservations, summaries, config, architectureObs);\n } finally {\n this.store.close();\n }\n }\n\n /**\n * Write context to file for agent to read on-demand\n */\n writeContextFile(projectPath: string = '.'): string {\n const context = this.generateContext(projectPath);\n const contextPath = require('path').join(projectPath, 'heraspec', 'memory', 'context.md');\n\n const fs = require('fs');\n const dir = require('path').dirname(contextPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n fs.writeFileSync(contextPath, context, 'utf-8');\n return contextPath;\n }\n\n // ============ Private ============\n\n private renderEmptyState(): string {\n return `# HeraSpec Memory Context\n\n> No observations or session summaries recorded yet.\n> Memory will build up as you work on this project.\n>\n> **How it works (complementary approach):**\n> - Use \\`heraspec memory log\\` to record important observations\n> - Use \\`heraspec memory summarize\\` at end of sessions\n> - Use \\`heraspec memory search\\` to check history before implementing features\n> - This file updates when you run \\`heraspec memory context\\`\n`;\n }\n\n private buildContextOutput(\n observations: Observation[],\n summaries: SessionSummary[],\n config: ContextConfig,\n architectureObs: Observation | null = null\n ): string {\n const lines: string[] = [];\n let tokenBudget = config.maxTokens;\n\n // Header\n lines.push('# HeraSpec Memory Context');\n lines.push('');\n lines.push(`> ${observations.length} observations, ${summaries.length} session summaries`);\n lines.push(`> Generated: ${new Date().toISOString()}`);\n lines.push('');\n tokenBudget -= 30; // header tokens\n\n // Architecture Map (Pinned at the top if exists)\n if (architectureObs) {\n lines.push('## Project Architecture');\n lines.push('');\n const archBlock = this.renderFullObservation(architectureObs);\n const archTokens = estimateTokens(archBlock);\n \n if (tokenBudget >= archTokens) {\n lines.push(archBlock);\n tokenBudget -= archTokens;\n } else {\n lines.push(`> Architecture map is too large to include. Use \\`heraspec memory search --id ${architectureObs.id}\\` to view it.\\n`);\n }\n }\n\n // Most recent session summary\n if (config.showLastSummary && summaries.length > 0) {\n const latest = summaries[0];\n const summaryBlock = this.renderSummary(latest);\n const summaryTokens = estimateTokens(summaryBlock);\n\n if (tokenBudget >= summaryTokens) {\n lines.push(summaryBlock);\n lines.push('');\n tokenBudget -= summaryTokens;\n }\n }\n\n // Recent observations - full details for most recent N\n const fullObs = observations.slice(0, config.fullObservationCount);\n if (fullObs.length > 0) {\n lines.push('## Recent Activity (Full Details)');\n lines.push('');\n\n for (const obs of fullObs) {\n const obsBlock = this.renderFullObservation(obs);\n const obsTokens = estimateTokens(obsBlock);\n\n if (tokenBudget >= obsTokens) {\n lines.push(obsBlock);\n tokenBudget -= obsTokens;\n } else {\n break;\n }\n }\n }\n\n // Remaining observations - index only (progressive disclosure)\n const indexObs = observations.slice(config.fullObservationCount);\n if (indexObs.length > 0) {\n lines.push('## Earlier Activity (Index)');\n lines.push('');\n lines.push('| ID | Date | Type | Title | Tokens |');\n lines.push('|----|------|------|-------|--------|');\n\n for (const obs of indexObs) {\n const date = new Date(obs.createdAtEpoch).toLocaleDateString('en-US', {\n month: 'short', day: 'numeric',\n });\n const icon = OBSERVATION_TYPE_ICONS[obs.type] || '\uD83D\uDCCC';\n const tokens = estimateTokens(obs.narrative);\n const row = `| #${obs.id} | ${date} | ${icon} | ${obs.title} | ~${tokens} |`;\n const rowTokens = estimateTokens(row);\n\n if (tokenBudget >= rowTokens) {\n lines.push(row);\n tokenBudget -= rowTokens;\n } else {\n lines.push(`| ... | | | ${indexObs.length - indexObs.indexOf(obs)} more observations | |`);\n break;\n }\n }\n\n lines.push('');\n lines.push('> Use `heraspec memory search --id <ID>` to see full details of any observation.');\n }\n\n // Previous session summaries (compact)\n if (summaries.length > 1) {\n const olderSummaries = summaries.slice(1);\n lines.push('');\n lines.push('## Previous Sessions');\n lines.push('');\n\n for (const sum of olderSummaries) {\n const date = new Date(sum.createdAtEpoch).toLocaleDateString('en-US', {\n month: 'short', day: 'numeric',\n });\n const compact = `- **${date}**: ${sum.request || 'Untitled'} \u2192 ${sum.completed || 'No summary'}`;\n const compactTokens = estimateTokens(compact);\n\n if (tokenBudget >= compactTokens) {\n lines.push(compact);\n tokenBudget -= compactTokens;\n }\n }\n }\n\n return lines.join('\\n');\n }\n\n private renderSummary(summary: SessionSummary): string {\n const lines: string[] = [];\n const date = new Date(summary.createdAtEpoch).toLocaleDateString('en-US', {\n year: 'numeric', month: 'short', day: 'numeric',\n });\n\n lines.push(`## Last Session (${date})`);\n lines.push('');\n\n if (summary.request) lines.push(`**Request:** ${summary.request}`);\n if (summary.investigated) lines.push(`**Investigated:** ${summary.investigated}`);\n if (summary.learned) lines.push(`**Learned:** ${summary.learned}`);\n if (summary.completed) lines.push(`**Completed:** ${summary.completed}`);\n if (summary.nextSteps) lines.push(`**Next Steps:** ${summary.nextSteps}`);\n\n if (summary.filesEdited.length > 0) {\n lines.push(`**Files edited:** ${summary.filesEdited.join(', ')}`);\n }\n\n return lines.join('\\n');\n }\n\n private renderFullObservation(obs: Observation): string {\n const lines: string[] = [];\n const icon = OBSERVATION_TYPE_ICONS[obs.type] || '\uD83D\uDCCC';\n const time = new Date(obs.createdAtEpoch).toLocaleString('en-US', {\n month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit',\n });\n\n lines.push(`### ${icon} #${obs.id} \u2014 ${obs.title}`);\n lines.push(`*${time} | ${obs.type} | Concepts: ${obs.concepts.join(', ') || 'none'}*`);\n lines.push('');\n\n if (obs.narrative) {\n lines.push(obs.narrative);\n lines.push('');\n }\n\n if (obs.filesModified.length > 0) {\n lines.push(`**Files modified:** ${obs.filesModified.join(', ')}`);\n }\n\n lines.push('---');\n lines.push('');\n\n return lines.join('\\n');\n }\n}\n", "/**\n * HeraSpec Memory Config Advisor\n * Auto-detects project scale and recommends optimal config adjustments\n */\nimport type { ContextConfig, MemoryStatus} from './memory-types.js';\nimport { loadContextConfig } from './context-config.js';\n\nexport interface ConfigRecommendation {\n setting: string;\n currentValue: number | boolean;\n recommendedValue: number | boolean;\n reason: string;\n impact: string;\n}\n\nexport interface ConfigAdvice {\n projectScale: 'small' | 'medium' | 'large' | 'enterprise';\n recommendations: ConfigRecommendation[];\n hasChanges: boolean;\n summary: string;\n}\n\n/**\n * Thresholds for project scale detection\n */\nconst SCALE_THRESHOLDS = {\n small: { maxObs: 50, maxSum: 10 },\n medium: { maxObs: 500, maxSum: 50 },\n large: { maxObs: 2000, maxSum: 200 },\n // enterprise: above large\n};\n\n/**\n * Optimal configs per project scale\n */\nconst SCALE_CONFIGS: Record<string, Partial<ContextConfig>> = {\n small: {\n totalObservationCount: 30,\n fullObservationCount: 3,\n sessionCount: 3,\n maxTokens: 4000,\n },\n medium: {\n totalObservationCount: 50,\n fullObservationCount: 5,\n sessionCount: 5,\n maxTokens: 6000,\n },\n large: {\n totalObservationCount: 80,\n fullObservationCount: 5,\n sessionCount: 8,\n maxTokens: 8000,\n },\n enterprise: {\n totalObservationCount: 100,\n fullObservationCount: 7,\n sessionCount: 10,\n maxTokens: 10000,\n },\n};\n\n/**\n * Analyze memory status and recommend config changes\n */\nexport function analyzeAndRecommend(status: MemoryStatus, projectPath: string = '.'): ConfigAdvice {\n const currentConfig = loadContextConfig(projectPath);\n const scale = detectScale(status);\n const optimal = SCALE_CONFIGS[scale];\n const recommendations: ConfigRecommendation[] = [];\n\n // Check totalObservationCount\n if (currentConfig.totalObservationCount !== optimal.totalObservationCount) {\n const current = currentConfig.totalObservationCount;\n const recommended = optimal.totalObservationCount!;\n\n if (status.observationCount > current * 0.8) {\n recommendations.push({\n setting: 'totalObservationCount',\n currentValue: current,\n recommendedValue: recommended,\n reason: `D\u1EF1 \u00E1n c\u00F3 ${status.observationCount} observations, context \u0111ang hi\u1EC3n th\u1ECB ${current} \u2014 ${current < recommended ? 'c\u00F3 th\u1EC3 b\u1ECF l\u1EE1 context quan tr\u1ECDng' : '\u0111ang hi\u1EC3n th\u1ECB qu\u00E1 nhi\u1EC1u'}`,\n impact: current < recommended\n ? `T\u0103ng t\u1EA7m nh\u00ECn t\u1EEB ${current} \u2192 ${recommended} observations (+${(recommended - current) * 15} tokens index)`\n : `Gi\u1EA3m t\u1EEB ${current} \u2192 ${recommended} observations (ti\u1EBFt ki\u1EC7m ~${(current - recommended) * 15} tokens)`,\n });\n }\n }\n\n // Check fullObservationCount\n if (currentConfig.fullObservationCount !== optimal.fullObservationCount) {\n recommendations.push({\n setting: 'fullObservationCount',\n currentValue: currentConfig.fullObservationCount,\n recommendedValue: optimal.fullObservationCount!,\n reason: `Scale \"${scale}\" t\u1ED1i \u01B0u v\u1EDBi ${optimal.fullObservationCount} full observations`,\n impact: `${currentConfig.fullObservationCount < optimal.fullObservationCount! ? 'Th\u00EAm' : 'Gi\u1EA3m'} narrative \u0111\u1EA7y \u0111\u1EE7 \u2192 ${currentConfig.fullObservationCount < optimal.fullObservationCount! ? 'context phong ph\u00FA h\u01A1n' : 'ti\u1EBFt ki\u1EC7m tokens'}`,\n });\n }\n\n // Check sessionCount\n if (currentConfig.sessionCount !== optimal.sessionCount) {\n if (status.summaryCount > currentConfig.sessionCount * 2) {\n recommendations.push({\n setting: 'sessionCount',\n currentValue: currentConfig.sessionCount,\n recommendedValue: optimal.sessionCount!,\n reason: `C\u00F3 ${status.summaryCount} summaries nh\u01B0ng ch\u1EC9 hi\u1EC7n ${currentConfig.sessionCount}`,\n impact: `T\u0103ng session history \u2192 agent hi\u1EC3u r\u00F5 h\u01A1n d\u00F2ng th\u1EDDi gian d\u1EF1 \u00E1n`,\n });\n }\n }\n\n // Check maxTokens\n if (currentConfig.maxTokens !== optimal.maxTokens) {\n const estimatedContextTokens = estimateContextCost(optimal, status);\n\n if (estimatedContextTokens > currentConfig.maxTokens * 0.85) {\n recommendations.push({\n setting: 'maxTokens',\n currentValue: currentConfig.maxTokens,\n recommendedValue: optimal.maxTokens!,\n reason: `Context \u01B0\u1EDBc t\u00EDnh ~${estimatedContextTokens} tokens, \u0111ang c\u1EAFt b\u1EDBt v\u00EC limit ${currentConfig.maxTokens}`,\n impact: `T\u0103ng budget \u2192 context \u0111\u1EA7y \u0111\u1EE7 h\u01A1n, ch\u1EC9 chi\u1EBFm ${((optimal.maxTokens! / 128000) * 100).toFixed(1)}% context window nh\u1ECF nh\u1EA5t (128K)`,\n });\n }\n }\n\n // Additional advice: prune old data\n if (status.observationCount > 1000) {\n const daysSinceOldest = status.oldestObservation\n ? Math.floor((Date.now() - new Date(status.oldestObservation).getTime()) / (1000 * 60 * 60 * 24))\n : 0;\n\n if (daysSinceOldest > 180) {\n recommendations.push({\n setting: 'prune',\n currentValue: daysSinceOldest,\n recommendedValue: 180,\n reason: `C\u00F3 observations c\u0169 ${daysSinceOldest} ng\u00E0y \u2014 \u00EDt gi\u00E1 tr\u1ECB cho context hi\u1EC7n t\u1EA1i`,\n impact: `Ch\u1EA1y \\`heraspec memory prune 180\\` \u0111\u1EC3 x\u00F3a observations c\u0169 h\u01A1n 6 th\u00E1ng`,\n });\n }\n }\n\n const hasChanges = recommendations.filter(r => r.setting !== 'prune').length > 0;\n\n return {\n projectScale: scale,\n recommendations,\n hasChanges,\n summary: buildSummary(scale, status, recommendations),\n };\n}\n\n/**\n * Detect project scale from memory status\n */\nfunction detectScale(status: MemoryStatus): 'small' | 'medium' | 'large' | 'enterprise' {\n const obsCount = status.observationCount;\n const sumCount = status.summaryCount;\n\n if (obsCount <= SCALE_THRESHOLDS.small.maxObs && sumCount <= SCALE_THRESHOLDS.small.maxSum) {\n return 'small';\n }\n if (obsCount <= SCALE_THRESHOLDS.medium.maxObs && sumCount <= SCALE_THRESHOLDS.medium.maxSum) {\n return 'medium';\n }\n if (obsCount <= SCALE_THRESHOLDS.large.maxObs && sumCount <= SCALE_THRESHOLDS.large.maxSum) {\n return 'large';\n }\n return 'enterprise';\n}\n\n/**\n * Estimate context token cost for given config\n */\nfunction estimateContextCost(config: Partial<ContextConfig>, status: MemoryStatus): number {\n const fullObs = Math.min(config.fullObservationCount || 5, status.observationCount);\n const indexObs = Math.min(\n (config.totalObservationCount || 50) - fullObs,\n Math.max(0, status.observationCount - fullObs)\n );\n const sessions = Math.min(config.sessionCount || 5, status.summaryCount);\n\n // Estimates\n const headerTokens = 30;\n const fullObsTokens = fullObs * 350; // ~350 tokens avg per full observation\n const indexTokens = indexObs * 15; // ~15 tokens per index row\n const summaryTokens = sessions > 0 ? 300 + (sessions - 1) * 30 : 0; // first full, rest compact\n\n return headerTokens + fullObsTokens + indexTokens + summaryTokens;\n}\n\n/**\n * Build human-readable summary\n */\nfunction buildSummary(\n scale: string,\n status: MemoryStatus,\n recommendations: ConfigRecommendation[]\n): string {\n const scaleLabels: Record<string, string> = {\n small: '\uD83D\uDCE6 Nh\u1ECF (< 50 observations)',\n medium: '\uD83D\uDCCA Trung b\u00ECnh (50-500 observations)',\n large: '\uD83C\uDFE2 L\u1EDBn (500-2000 observations)',\n enterprise: '\uD83C\uDFD7\uFE0F Enterprise (2000+ observations)',\n };\n\n const lines: string[] = [];\n lines.push(`Quy m\u00F4 d\u1EF1 \u00E1n: ${scaleLabels[scale]}`);\n lines.push(`Observations: ${status.observationCount} | Summaries: ${status.summaryCount}`);\n\n if (recommendations.length === 0) {\n lines.push(`\\n\u2705 C\u1EA5u h\u00ECnh hi\u1EC7n t\u1EA1i \u0111\u00E3 t\u1ED1i \u01B0u cho quy m\u00F4 d\u1EF1 \u00E1n.`);\n } else {\n const configChanges = recommendations.filter(r => r.setting !== 'prune');\n if (configChanges.length > 0) {\n lines.push(`\\n\u26A0\uFE0F C\u00F3 ${configChanges.length} \u0111\u1EC1 xu\u1EA5t \u0111i\u1EC1u ch\u1EC9nh config.`);\n }\n const pruneAdvice = recommendations.find(r => r.setting === 'prune');\n if (pruneAdvice) {\n lines.push(`\uD83D\uDDD1\uFE0F N\u00EAn d\u1ECDn d\u1EB9p observations c\u0169.`);\n }\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Generate the new config JSON to write\n */\nexport function buildOptimizedConfig(\n status: MemoryStatus,\n projectPath: string = '.'\n): { config: ContextConfig; advice: ConfigAdvice } {\n const advice = analyzeAndRecommend(status, projectPath);\n const currentConfig = loadContextConfig(projectPath);\n\n // Apply recommendations\n const newConfig = { ...currentConfig };\n\n for (const rec of advice.recommendations) {\n if (rec.setting === 'prune') continue; // prune is a command, not config\n\n switch (rec.setting) {\n case 'totalObservationCount':\n newConfig.totalObservationCount = rec.recommendedValue as number;\n break;\n case 'fullObservationCount':\n newConfig.fullObservationCount = rec.recommendedValue as number;\n break;\n case 'sessionCount':\n newConfig.sessionCount = rec.recommendedValue as number;\n break;\n case 'maxTokens':\n newConfig.maxTokens = rec.recommendedValue as number;\n break;\n }\n }\n\n return { config: newConfig, advice };\n}\n", "/**\n * HeraSpec Memory Command\n * CLI commands for project memory management\n */\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { MemoryStore } from '../core/memory/memory-store.js';\nimport { MemorySearch } from '../core/memory/memory-search.js';\nimport { MemoryVector } from '../core/memory/memory-vector.js';\nimport { ContextGenerator } from '../core/memory/context-generator.js';\nimport { OBSERVATION_TYPES, OBSERVATION_TYPE_ICONS, estimateTokens } from '../core/memory/memory-types.js';\nimport type { ObservationType } from '../core/memory/memory-types.js';\nimport { analyzeAndRecommend, buildOptimizedConfig } from '../core/memory/config-advisor.js';\nimport { saveContextConfig } from '../core/memory/context-config.js';\nimport { FileSystemUtils } from '../utils/file-system.js';\nimport path from 'path';\nimport { SPECS_DIR_NAME, CHANGES_DIR_NAME, ARCHIVES_DIR_NAME, HERASPEC_DIR_NAME } from '../core/config.js';\n\nexport class MemoryCommand {\n /**\n * heraspec memory log - Record an observation\n */\n async log(options: {\n type: string;\n title: string;\n narrative?: string;\n concepts?: string;\n filesModified?: string;\n filesRead?: string;\n discoveryTokens?: string;\n sessionId?: string;\n project?: string;\n }, projectPath: string = '.'): Promise<void> {\n const spinner = ora('Recording observation...').start();\n\n try {\n // Validate type\n if (!OBSERVATION_TYPES.includes(options.type as ObservationType)) {\n spinner.fail(`Invalid type \"${options.type}\". Valid types: ${OBSERVATION_TYPES.join(', ')}`);\n process.exitCode = 1;\n return;\n }\n\n const store = new MemoryStore(projectPath);\n store.open();\n\n try {\n // Generate embedding\n const textToEmbed = `${options.title} ${options.narrative || ''} ${options.concepts || ''}`.trim();\n let embedding: number[] | undefined;\n try { embedding = await MemoryVector.generateEmbedding(textToEmbed); } catch (e) { /* ignore */ }\n\n const obs = store.addObservation({\n type: options.type as ObservationType,\n title: options.title,\n narrative: options.narrative || '',\n concepts: options.concepts ? options.concepts.split(',').map(c => c.trim()) : [],\n filesModified: options.filesModified ? options.filesModified.split(',').map(f => f.trim()) : [],\n filesRead: options.filesRead ? options.filesRead.split(',').map(f => f.trim()) : [],\n discoveryTokens: options.discoveryTokens ? parseInt(options.discoveryTokens, 10) : 0,\n sessionId: options.sessionId,\n project: options.project,\n embedding,\n });\n\n const icon = OBSERVATION_TYPE_ICONS[obs.type] || '\uD83D\uDCCC';\n spinner.succeed(`${icon} Observation #${obs.id} recorded: ${obs.title}`);\n\n if (obs.concepts.length > 0) {\n console.log(` Concepts: ${chalk.cyan(obs.concepts.join(', '))}`);\n }\n if (obs.filesModified.length > 0) {\n console.log(` Files: ${chalk.yellow(obs.filesModified.join(', '))}`);\n }\n } finally {\n store.close();\n }\n } catch (error) {\n spinner.fail(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exitCode = 1;\n }\n\n // Auto-optimize memory config silently\n try {\n await this.optimize({ yes: true, silent: true }, projectPath);\n } catch (e) {\n // Ignore auto-optimize errors\n }\n }\n\n /**\n * heraspec memory query - Semantic search using Vector embeddings\n */\n async query(question: string, options: { limit?: number; project?: string; } = {}, projectPath: string = '.'): Promise<void> {\n const spinner = ora('Generating embedding for query...').start();\n try {\n const store = new MemoryStore(projectPath);\n store.open();\n try {\n const observations = store.getRecentObservations(options.project, 5000); // Fetch all to rank\n \n spinner.text = 'Calculating semantic similarity...';\n const results = await MemoryVector.search(question, observations, options.limit || 10);\n \n spinner.stop();\n if (results.length === 0) {\n console.log(chalk.yellow('\\nNo relevant observations found using vector search.\\n'));\n return;\n }\n\n console.log(chalk.cyan('\\n\uD83D\uDD0D Semantic Search Results:\\n'));\n const search = new MemorySearch(store);\n console.log(search.formatResultsAsIndex(results, question));\n console.log(chalk.gray('\\n\uD83D\uDCA1 Note: Results are ranked by semantic similarity, not chronologically.'));\n } finally {\n store.close();\n }\n } catch (error) {\n spinner.fail(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exitCode = 1;\n }\n }\n\n /**\n * heraspec memory search - Search observations\n */\n async search(query: string, options: {\n type?: string;\n concepts?: string;\n files?: string;\n limit?: number;\n id?: number;\n project?: string;\n } = {}, projectPath: string = '.'): Promise<void> {\n try {\n const store = new MemoryStore(projectPath);\n store.open();\n\n try {\n // If --id specified, show full details of that observation\n if (options.id) {\n const obs = store.getObservationById(options.id);\n if (!obs) {\n console.log(chalk.red(`Observation #${options.id} not found.`));\n process.exitCode = 1;\n return;\n }\n\n const icon = OBSERVATION_TYPE_ICONS[obs.type] || '\uD83D\uDCCC';\n console.log(`\\n${icon} Observation #${obs.id} \u2014 ${obs.title}`);\n console.log(`${chalk.gray('Type:')} ${obs.type}`);\n console.log(`${chalk.gray('Date:')} ${obs.createdAt}`);\n console.log(`${chalk.gray('Concepts:')} ${obs.concepts.join(', ') || 'none'}`);\n console.log(`${chalk.gray('Session:')} ${obs.sessionId}`);\n if (obs.filesRead.length > 0) {\n console.log(`${chalk.gray('Files read:')} ${obs.filesRead.join(', ')}`);\n }\n if (obs.filesModified.length > 0) {\n console.log(`${chalk.gray('Files modified:')} ${obs.filesModified.join(', ')}`);\n }\n console.log(`${chalk.gray('Tokens:')} ~${estimateTokens(obs.narrative)}`);\n console.log(`\\n${obs.narrative || '(no narrative)'}\\n`);\n return;\n }\n\n const search = new MemorySearch(store);\n const results = search.searchObservations({\n query: query || undefined,\n type: options.type as ObservationType | undefined,\n concepts: options.concepts ? options.concepts.split(',').map(c => c.trim()) : undefined,\n files: options.files ? options.files.split(',').map(f => f.trim()) : undefined,\n limit: options.limit || 20,\n project: options.project,\n });\n\n console.log('\\n' + search.formatResultsAsIndex(results, query || undefined));\n } finally {\n store.close();\n }\n } catch (error) {\n console.error(chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`));\n process.exitCode = 1;\n }\n }\n\n /**\n * heraspec memory context - Generate context for AI agent\n */\n async context(options: {\n output?: string;\n maxTokens?: number;\n } = {}, projectPath: string = '.'): Promise<void> {\n const spinner = ora('Generating context...').start();\n\n try {\n const generator = new ContextGenerator(projectPath);\n\n if (options.output === 'file') {\n const contextPath = generator.writeContextFile(projectPath);\n spinner.succeed(`Context written to: ${contextPath}`);\n } else {\n spinner.stop();\n const context = generator.generateContext(projectPath);\n console.log(context);\n }\n } catch (error) {\n spinner.fail(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exitCode = 1;\n }\n }\n\n /**\n * heraspec memory summarize - Create a session summary\n */\n async summarize(options: {\n request: string;\n investigated?: string;\n learned?: string;\n completed?: string;\n nextSteps?: string;\n filesRead?: string;\n filesEdited?: string;\n sessionId?: string;\n project?: string;\n }, projectPath: string = '.'): Promise<void> {\n const spinner = ora('Creating session summary...').start();\n\n try {\n const store = new MemoryStore(projectPath);\n store.open();\n\n try {\n const summary = store.addSummary({\n request: options.request,\n investigated: options.investigated || '',\n learned: options.learned || '',\n completed: options.completed || '',\n nextSteps: options.nextSteps || '',\n filesRead: options.filesRead ? options.filesRead.split(',').map(f => f.trim()) : [],\n filesEdited: options.filesEdited ? options.filesEdited.split(',').map(f => f.trim()) : [],\n sessionId: options.sessionId,\n project: options.project,\n });\n\n spinner.succeed(`\uD83C\uDFAF Session summary #${summary.id} created`);\n console.log(` Request: ${chalk.white(summary.request)}`);\n if (summary.completed) console.log(` Completed: ${chalk.green(summary.completed)}`);\n if (summary.nextSteps) console.log(` Next steps: ${chalk.yellow(summary.nextSteps)}`);\n } finally {\n store.close();\n }\n } catch (error) {\n spinner.fail(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exitCode = 1;\n }\n\n // Auto-optimize memory config silently\n try {\n await this.optimize({ yes: true, silent: true }, projectPath);\n } catch (e) {\n // Ignore auto-optimize errors\n }\n }\n\n /**\n * heraspec memory status - Show memory statistics\n */\n async status(projectPath: string = '.'): Promise<void> {\n try {\n const store = new MemoryStore(projectPath);\n store.open();\n\n try {\n const status = store.getStatus();\n\n console.log('\\n\uD83D\uDCCA HeraSpec Memory Status\\n');\n console.log('\u2550'.repeat(50));\n console.log(` Observations: ${chalk.cyan(String(status.observationCount))}`);\n console.log(` Summaries: ${chalk.cyan(String(status.summaryCount))}`);\n console.log(` Sessions: ${chalk.cyan(String(status.sessionCount))}`);\n console.log(` DB Size: ${chalk.cyan(this.formatBytes(status.dbSizeBytes))}`);\n console.log(` Total Tokens: ${chalk.cyan('~' + status.estimatedTotalTokens)}`);\n\n if (status.oldestObservation) {\n console.log(` Oldest: ${chalk.gray(status.oldestObservation)}`);\n console.log(` Newest: ${chalk.gray(status.newestObservation || '')}`);\n }\n\n if (status.topConcepts.length > 0) {\n console.log('\\n Top Concepts:');\n for (const { concept, count } of status.topConcepts.slice(0, 5)) {\n console.log(` ${chalk.cyan(concept)} (${count})`);\n }\n }\n\n if (status.topFiles.length > 0) {\n console.log('\\n Top Files:');\n for (const { file, count } of status.topFiles.slice(0, 5)) {\n console.log(` ${chalk.yellow(file)} (${count})`);\n }\n }\n\n console.log('\\n' + '\u2550'.repeat(50));\n\n // Auto-detect and show config recommendations\n const advice = analyzeAndRecommend(status, projectPath);\n\n const scaleIcons: Record<string, string> = {\n small: '\uD83D\uDCE6', medium: '\uD83D\uDCCA', large: '\uD83C\uDFE2', enterprise: '\uD83C\uDFD7\uFE0F',\n };\n console.log(`\\n Scale: ${scaleIcons[advice.projectScale] || '\uD83D\uDCCA'} ${advice.projectScale}`);\n\n if (advice.recommendations.length > 0) {\n console.log(`\\n ${chalk.yellow('\u26A0\uFE0F Config recommendations detected:')}`); for (const rec of advice.recommendations) {\n if (rec.setting === 'prune') {\n console.log(` \uD83D\uDDD1\uFE0F ${chalk.gray(rec.reason)}`);\n console.log(` \u2192 ${chalk.cyan(rec.impact)}`);\n } else {\n console.log(` ${chalk.white(rec.setting)}: ${chalk.red(String(rec.currentValue))} \u2192 ${chalk.green(String(rec.recommendedValue))}`);\n console.log(` ${chalk.gray(rec.reason)}`);\n }\n }\n if (advice.hasChanges) {\n console.log(`\\n \uD83D\uDCA1 Run ${chalk.cyan('heraspec memory optimize')} to apply recommendations.`);\n }\n } else {\n console.log(`\\n ${chalk.green('\u2705 Config is optimal for current project scale.')}`);\n }\n\n console.log('\\n');\n } finally {\n store.close();\n }\n } catch (error) {\n console.error(chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`));\n process.exitCode = 1;\n }\n }\n\n /**\n * heraspec memory timeline - Show observation timeline\n */\n async timeline(options: {\n limit?: number;\n project?: string;\n } = {}, projectPath: string = '.'): Promise<void> {\n try {\n const store = new MemoryStore(projectPath);\n store.open();\n\n try {\n const search = new MemorySearch(store);\n const items = search.getTimeline({\n depthBefore: options.limit || 20,\n depthAfter: 0,\n project: options.project,\n });\n\n console.log('\\n' + search.formatTimeline(items));\n } finally {\n store.close();\n }\n } catch (error) {\n console.error(chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`));\n process.exitCode = 1;\n }\n }\n\n /**\n * heraspec memory prune - Delete old observations\n */\n async prune(days: number, options: { project?: string } = {}, projectPath: string = '.'): Promise<void> {\n const spinner = ora(`Pruning observations older than ${days} days...`).start();\n\n try {\n const store = new MemoryStore(projectPath);\n store.open();\n\n try {\n const deleted = store.pruneObservations(days, options.project);\n spinner.succeed(`Pruned ${deleted} observation(s) older than ${days} days.`);\n } finally {\n store.close();\n }\n } catch (error) {\n spinner.fail(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exitCode = 1;\n }\n }\n\n private formatBytes(bytes: number): string {\n if (bytes === 0) return '0 B';\n const units = ['B', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(1024));\n return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${units[i]}`;\n }\n\n /**\n * heraspec memory optimize - Auto-detect and apply optimal config\n */\n async optimize(options: { yes?: boolean; silent?: boolean } = {}, projectPath: string = '.'): Promise<void> {\n try {\n const store = new MemoryStore(projectPath);\n store.open();\n\n try {\n const status = store.getStatus();\n const { config: newConfig, advice } = buildOptimizedConfig(status, projectPath);\n\n const scaleLabels: Record<string, string> = {\n small: '\uD83D\uDCE6 Small (< 50 observations)',\n medium: '\uD83D\uDCCA Medium (50-500 observations)',\n large: '\uD83C\uDFE2 Large (500-2000 observations)',\n enterprise: '\uD83C\uDFD7\uFE0F Enterprise (2000+ observations)',\n };\n\n if (!options.silent) {\n console.log(`\\n\uD83D\uDD0D HeraSpec Memory Config Optimizer\\n`);\n console.log(`Project scale: ${scaleLabels[advice.projectScale]}`);\n console.log(`Observations: ${status.observationCount} | Summaries: ${status.summaryCount}\\n`);\n }\n\n if (!advice.hasChanges) {\n if (!options.silent) {\n console.log(chalk.green('\u2705 Current config is already optimal for your project scale.\\n'));\n }\n return;\n }\n\n if (options.silent && options.yes) {\n // In silent mode, just apply and return\n saveContextConfig(newConfig, projectPath);\n return;\n }\n\n if (!options.silent) {\n console.log('Proposed changes:\\n');\n }\n console.log(' \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510');\n console.log(' \u2502 Setting \u2502 Current \u2502 Recommended \u2502');\n console.log(' \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524');\n\n for (const rec of advice.recommendations) {\n if (rec.setting === 'prune') continue;\n const name = rec.setting.padEnd(23);\n const current = String(rec.currentValue).padEnd(8);\n const recommended = String(rec.recommendedValue).padEnd(11);\n console.log(` \u2502 ${name} \u2502 ${chalk.red(current)} \u2502 ${chalk.green(recommended)} \u2502`);\n }\n\n console.log(' \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n');\n\n // Show reasons\n for (const rec of advice.recommendations) {\n if (rec.setting === 'prune') {\n console.log(` \uD83D\uDDD1\uFE0F ${rec.reason}`);\n console.log(` \u2192 ${chalk.cyan(rec.impact)}\\n`);\n } else {\n console.log(` ${chalk.white(rec.setting)}: ${rec.reason}`);\n }\n }\n\n // Confirm\n if (options.yes) {\n saveContextConfig(newConfig, projectPath);\n console.log(chalk.green('\\n\u2705 Config updated successfully!'));\n console.log(chalk.gray(' Location: heraspec/memory/config.json\\n'));\n return;\n }\n\n // Interactive confirmation\n const { confirm } = await import('@inquirer/prompts');\n const answer = await confirm({\n message: 'Apply these config changes?',\n default: true,\n });\n\n if (answer) {\n saveContextConfig(newConfig, projectPath);\n console.log(chalk.green('\\n\u2705 Config updated successfully!'));\n console.log(chalk.gray(' Location: heraspec/memory/config.json\\n'));\n } else {\n console.log(chalk.gray('\\nNo changes made.\\n'));\n }\n } finally {\n store.close();\n }\n } catch (error) {\n console.error(chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`));\n process.exitCode = 1;\n }\n }\n\n /**\n * heraspec memory bootstrap - Import historical specs and archives into memory\n */\n async bootstrap(options: { yes?: boolean } = {}, projectPath: string = '.'): Promise<void> {\n console.log(chalk.cyan('\\n\uD83D\uDE80 Bootstrapping Project Memory from Historical Specs...\\n'));\n\n const heraspecPath = path.join(projectPath, HERASPEC_DIR_NAME);\n const specsDir = path.join(heraspecPath, SPECS_DIR_NAME);\n const archivesDir = path.join(heraspecPath, ARCHIVES_DIR_NAME);\n const changesDir = path.join(heraspecPath, CHANGES_DIR_NAME);\n\n // Collect all md files\n const mdFiles: string[] = [];\n\n const scanDir = async (dirPath: string) => {\n if (!(await FileSystemUtils.fileExists(dirPath))) return;\n const entries = await FileSystemUtils.readDirectory(dirPath);\n for (const entry of entries) {\n const fullPath = path.join(dirPath, entry);\n const stat = await FileSystemUtils.stat(fullPath);\n if (stat.isDirectory()) {\n // Inside a change/archive folder, look for specific md files like the spec itself\n const subEntries = await FileSystemUtils.readDirectory(fullPath);\n for (const sub of subEntries) {\n if (sub.endsWith('.md') && sub !== 'tasks.md' && sub !== 'project.md') {\n mdFiles.push(path.join(fullPath, sub));\n }\n }\n } else if (entry.endsWith('.md')) {\n mdFiles.push(fullPath);\n }\n }\n };\n\n await scanDir(specsDir);\n await scanDir(archivesDir);\n // changesDir usually has the same structure as archives\n await scanDir(changesDir);\n\n if (mdFiles.length === 0) {\n console.log(chalk.yellow('No historical specs found.'));\n return;\n }\n\n if (!options.yes) {\n const { confirm } = await import('@inquirer/prompts');\n const answer = await confirm({\n message: `Found ${mdFiles.length} potential spec files. Proceed to extract and inject into memory?`,\n default: true,\n });\n if (!answer) {\n console.log(chalk.gray('Aborted.'));\n return;\n }\n }\n\n const spinner = ora('Parsing and migrating specs...').start();\n const store = new MemoryStore(projectPath);\n let parsedCount = 0;\n let skippedCount = 0;\n\n try {\n store.open();\n // To deduplicate we keep track of titles imported in this run or check DB\n const existingTitles = new Set(\n store.getRecentObservations(undefined, 1000).map(o => o.title.toLowerCase())\n );\n\n for (const filePath of mdFiles) {\n const content = await FileSystemUtils.readFile(filePath);\n const fileName = path.basename(filePath, '.md');\n\n // Extract Title: First H1 or fallback to filename\n const titleMatch = content.match(/^#\\s+(.+)$/m);\n const title = titleMatch ? titleMatch[1].trim() : fileName.replace(/-/g, ' ');\n\n if (existingTitles.has(title.toLowerCase())) {\n skippedCount++;\n continue;\n }\n\n // Extract Narrative: Text between ## Goal / ## Context and next ##\n let narrative = '';\n const narrativeMatch = content.match(/##\\s+(?:Goal|Context)\\s*\\n([\\s\\S]*?)(?=\\n##\\s|$)/i);\n if (narrativeMatch) {\n narrative = narrativeMatch[1].trim();\n } else {\n // Fallback, use the first paragraph\n const firstParagraph = content.replace(/^#.*\\n/, '').trim().split('\\n\\n')[0];\n narrative = firstParagraph || 'Bootstrapped historical spec.';\n }\n \n if (narrative.length > 500) narrative = narrative.substring(0, 500) + '...';\n\n // Extract Modified Files: paths matching #### [MODIFY] or [NEW] etc\n const filesModified: string[] = [];\n const fileRegex = /####\\s+\\[(?:MODIFY|NEW|DELETE)\\]\\s+(?:\\[(.*?)\\]|\\S+)\\s*\\((.*?)\\)/gi;\n let fmMatch;\n while ((fmMatch = fileRegex.exec(content)) !== null) {\n const fsPath = fmMatch[2]; // url/path part\n // Strip file:/// prefix\n const cleanPath = fsPath.replace(/^file:\\/\\/\\/?/, '');\n filesModified.push(cleanPath);\n }\n \n // Add minimal concept tags\n const concepts = ['legacy', 'bootstrapped'];\n if (filesModified.length > 0) concepts.push('files-modified');\n\n store.addObservation({\n type: 'feature',\n title: title,\n narrative: narrative,\n concepts: concepts,\n filesModified: filesModified.slice(0, 5), // Keep top 5 to not bloat limit\n });\n \n existingTitles.add(title.toLowerCase());\n parsedCount++;\n }\n\n spinner.succeed(`Migration complete: ${parsedCount} specs imported, ${skippedCount} skipped (already exist).`);\n console.log(chalk.gray(`\\nYou can verify by running: ${chalk.cyan('heraspec memory status')}`));\n\n } catch (error) {\n spinner.fail(`Metadata extraction failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exitCode = 1;\n } finally {\n store.close();\n }\n }\n\n /**\n * heraspec memory analytics - Show token usage and economic savings metrics\n */\n async analytics(options: { history?: boolean } = {}, projectPath: string = '.'): Promise<void> {\n try {\n const store = new MemoryStore(projectPath);\n store.open();\n\n try {\n const stats = store.getAnalytics();\n\n if (stats.length === 0) {\n console.log(chalk.yellow('\\n\uD83D\uDCCA No memory analytics data found yet.\\n'));\n return;\n }\n\n console.log(chalk.cyan('\\n\uD83D\uDCCA HeraSpec Memory Token Economics\\n'));\n console.log(chalk.gray('Comparing estimated token usage: With Memory vs Without Memory.\\n'));\n\n // Output table\n console.log('\u2550'.repeat(105));\n console.log(\n chalk.bold('Project'.padEnd(25)) + \n chalk.bold('Ops'.padEnd(6)) + \n chalk.bold('Tokens (With Memory)'.padEnd(22)) + \n chalk.bold('Tokens (Without)'.padEnd(20)) +\n chalk.bold('Savings'.padEnd(10)) +\n chalk.bold('DB Size'.padEnd(12))\n );\n console.log('\u2500'.repeat(105));\n\n let overallWith = 0;\n let overallWithout = 0;\n\n for (const s of stats) {\n overallWith += s.tokensWithMemory;\n overallWithout += s.tokensWithoutMemory;\n\n const pName = s.project.length > 22 ? s.project.substring(0, 20) + '..' : s.project.padEnd(25);\n const ops = String(s.totalOps).padEnd(6);\n \n // Format numbers\n const withMem = '~' + this.formatNumber(s.tokensWithMemory);\n const withoutMem = '~' + this.formatNumber(s.tokensWithoutMemory);\n const savings = chalk.green('+' + s.savingsPercent.toFixed(0) + '%');\n const dbSize = this.formatBytes(s.dbSizeBytes || 0);\n\n console.log(`${pName}${ops}${withMem.padEnd(22)}${withoutMem.padEnd(20)}${savings.padEnd(10)}${dbSize}`);\n }\n \n console.log('\u2500'.repeat(105));\n const totalSavingsPct = overallWithout > 0 ? ((overallWithout - overallWith) / overallWithout) * 100 : 0;\n console.log(\n chalk.bold('TOTAL'.padEnd(31)) + \n chalk.bold(`~${this.formatNumber(overallWith)}`.padEnd(22)) + \n chalk.bold(`~${this.formatNumber(overallWithout)}`.padEnd(20)) +\n chalk.bold(chalk.green(`+${totalSavingsPct.toFixed(0)}%`.padEnd(10)))\n );\n console.log('\u2550'.repeat(105) + '\\n');\n \n // Draw ASCII Chart for top 3\n console.log(chalk.cyan('\uD83D\uDCC8 Top Savings Chart (Tokens Avoided)\\n'));\n const MAX_BAR_LEN = 40;\n \n // Scale factor\n const maxSavings = Math.max(...stats.map(s => s.savingsTokens));\n \n for (const s of stats.slice(0, 5)) {\n if (s.savingsTokens <= 0) continue;\n const barLen = Math.ceil((s.savingsTokens / maxSavings) * MAX_BAR_LEN);\n const bar = '\u2588'.repeat(barLen);\n \n console.log(` ${s.project.substring(0, 15).padEnd(16)} | ${chalk.green(bar)} ${chalk.green('+' + this.formatNumber(s.savingsTokens))} tokens`);\n }\n\n console.log('\\n' + chalk.gray('\uD83D\uDCA1 Note: \"Tokens Without\" assume reading 50k tokens (average codebase context) per operation if memory was absent.') + '\\n');\n\n // History Table if requested\n if (options.history) {\n for (const s of stats) {\n const historyRows = store.getDbHistory(s.project, 13);\n if (historyRows.length === 0) continue;\n\n console.log(chalk.cyan(`\\n\uD83D\uDD52 Database Size History: [${s.project}] (Latest 13)`));\n console.log('\u2550'.repeat(60));\n console.log(\n chalk.bold('Date'.padEnd(25)) + \n chalk.bold('Size'.padEnd(15)) +\n chalk.bold('Delta')\n );\n console.log('\u2500'.repeat(60));\n\n for (let i = 0; i < historyRows.length; i++) {\n const row = historyRows[i];\n let deltaStr = '-';\n if (i < historyRows.length - 1) {\n const prev = historyRows[i + 1];\n const diff = row.dbSizeBytes - prev.dbSizeBytes;\n if (diff > 0) {\n deltaStr = chalk.green(`+${this.formatBytes(diff)}`);\n } else if (diff < 0) {\n deltaStr = chalk.yellow(`-${this.formatBytes(Math.abs(diff))}`);\n }\n }\n const dStr = new Date(row.createdAtEpoch).toLocaleString();\n console.log(`${dStr.padEnd(25)}${this.formatBytes(row.dbSizeBytes).padEnd(15)}${deltaStr}`);\n }\n console.log('\u2550'.repeat(60) + '\\n');\n }\n }\n\n } finally {\n store.close();\n }\n } catch (error) {\n console.error(chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`));\n process.exitCode = 1;\n }\n }\n\n /**\n * heraspec memory index - Scan project and generate architecture map observation\n */\n async index(options: { depth?: string, yes?: boolean } = {}, projectPath: string = '.'): Promise<void> {\n console.log(chalk.cyan('\\n\uD83D\uDD0D Generating Project Architecture Index...\\n'));\n \n if (!options.yes) {\n const { confirm } = await import('@inquirer/prompts');\n const answer = await confirm({\n message: 'This will scan the project directory structure and add an Architecture Map to the Memory DB. Proceed?',\n default: true,\n });\n if (!answer) {\n console.log(chalk.gray('Aborted.'));\n return;\n }\n }\n\n const spinner = ora('Scanning project structure...').start();\n try {\n const maxDepth = options.depth ? parseInt(options.depth, 10) : 3;\n \n const treeStr = await FileSystemUtils.generateTree(projectPath, maxDepth);\n \n if (!treeStr) {\n spinner.fail('Failed to generate tree or directory is empty.');\n process.exitCode = 1;\n return;\n }\n\n const narrative = `### Project Directory Structure (Depth: ${maxDepth})\\n\\n\\`\\`\\`text\\n${treeStr}\\n\\`\\`\\`\\n\\n> This observation provides a structural overview of the project. For deeper insights into specific files, use \\`heraspec explore outline <file>\\`.`;\n\n const store = new MemoryStore(projectPath);\n store.open();\n try {\n const obs = store.addObservation({\n type: 'discovery',\n title: 'Project Architecture and Directory Structure',\n narrative: narrative,\n concepts: ['architecture', 'structure', 'index'],\n });\n\n spinner.succeed(`Architecture Map saved to Memory DB as Observation #${obs.id}.`);\n console.log(chalk.gray(`\\nUse ${chalk.cyan('heraspec memory context')} to see the updated context map.`));\n } finally {\n store.close();\n }\n } catch (error) {\n spinner.fail(`Indexing failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exitCode = 1;\n }\n }\n\n private formatNumber(num: number): string {\n if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';\n if (num >= 1000) return (num / 1000).toFixed(1) + 'K';\n return String(Math.floor(num));\n }\n}\n", "/**\r\n * Skill Parser\r\n * Parses skill.md files to extract skill information\r\n */\r\nimport { readFileSync } from 'fs';\r\nimport path from 'path';\r\n\r\nexport interface SkillInfo {\r\n name: string;\r\n purpose: string;\r\n whenToUse: string[];\r\n steps: string[];\r\n inputs: string[];\r\n outputs: string[];\r\n toneAndRules: {\r\n codeStyle?: string;\r\n namingConventions?: string;\r\n limitations?: string[];\r\n };\r\n templates: string[];\r\n scripts: string[];\r\n examples: string[];\r\n relatedSkills: string[];\r\n skillPath: string;\r\n}\r\n\r\nexport class SkillParser {\r\n static parseSkill(skillPath: string, skillName: string): SkillInfo {\r\n const skillMdPath = path.join(skillPath, 'skill.md');\r\n \r\n try {\r\n const content = readFileSync(skillMdPath, 'utf-8');\r\n return this.parseSkillContent(content, skillName, skillPath);\r\n } catch (error) {\r\n throw new Error(`Failed to parse skill \"${skillName}\": ${error instanceof Error ? error.message : 'Unknown error'}`);\r\n }\r\n }\r\n\r\n private static parseSkillContent(content: string, skillName: string, skillPath: string): SkillInfo {\r\n const lines = content.split('\\n');\r\n \r\n const skill: Partial<SkillInfo> = {\r\n name: skillName,\r\n skillPath,\r\n purpose: '',\r\n whenToUse: [],\r\n steps: [],\r\n inputs: [],\r\n outputs: [],\r\n toneAndRules: {},\r\n templates: [],\r\n scripts: [],\r\n examples: [],\r\n relatedSkills: [],\r\n };\r\n\r\n let currentSection = '';\r\n let currentList: string[] = [];\r\n\r\n for (let i = 0; i < lines.length; i++) {\r\n const line = lines[i].trim();\r\n \r\n // Detect section headers\r\n if (line.match(/^##+\\s+/)) {\r\n // Save previous list\r\n this.saveList(currentSection, currentList, skill);\r\n currentList = [];\r\n \r\n const sectionName = line.replace(/^##+\\s+/, '').toLowerCase();\r\n currentSection = sectionName;\r\n \r\n // Extract purpose\r\n if (sectionName.includes('m\u1EE5c \u0111\u00EDch') || sectionName.includes('purpose')) {\r\n // Purpose is usually the next line or paragraph\r\n if (i + 1 < lines.length && lines[i + 1].trim()) {\r\n skill.purpose = lines[i + 1].trim();\r\n }\r\n }\r\n continue;\r\n }\r\n\r\n // Collect list items\r\n if (line.startsWith('- ') || line.startsWith('* ')) {\r\n const item = line.replace(/^[-*]\\s+/, '').trim();\r\n if (item) {\r\n currentList.push(item);\r\n }\r\n continue;\r\n }\r\n\r\n // Collect numbered steps\r\n if (line.match(/^\\d+\\.\\s+/)) {\r\n const step = line.replace(/^\\d+\\.\\s+/, '').trim();\r\n if (step) {\r\n skill.steps = skill.steps || [];\r\n skill.steps.push(step);\r\n }\r\n continue;\r\n }\r\n\r\n // Extract specific fields\r\n if (currentSection.includes('input')) {\r\n if (line.startsWith('- ')) {\r\n skill.inputs = skill.inputs || [];\r\n skill.inputs.push(line.replace(/^-\\s+/, ''));\r\n }\r\n }\r\n\r\n if (currentSection.includes('output')) {\r\n if (line.startsWith('- ')) {\r\n skill.outputs = skill.outputs || [];\r\n skill.outputs.push(line.replace(/^-\\s+/, ''));\r\n }\r\n }\r\n\r\n if (currentSection.includes('template')) {\r\n if (line.includes('.php') || line.includes('.md') || line.includes('.scss') || line.includes('.js') || line.includes('.sh')) {\r\n skill.templates = skill.templates || [];\r\n const templateName = line.match(/`([^`]+)`/) || line.match(/\\*\\*([^*]+)\\*\\*/);\r\n if (templateName) {\r\n skill.templates.push(templateName[1]);\r\n }\r\n }\r\n }\r\n\r\n if (currentSection.includes('script')) {\r\n if (line.includes('.sh') || line.includes('.py') || line.includes('.js')) {\r\n skill.scripts = skill.scripts || [];\r\n const scriptName = line.match(/`([^`]+)`/) || line.match(/\\*\\*([^*]+)\\*\\*/);\r\n if (scriptName) {\r\n skill.scripts.push(scriptName[1]);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // Save final list\r\n this.saveList(currentSection, currentList, skill);\r\n\r\n // Ensure all arrays exist\r\n return {\r\n name: skill.name || skillName,\r\n skillPath: skill.skillPath || skillPath,\r\n purpose: skill.purpose || 'No description available',\r\n whenToUse: skill.whenToUse || [],\r\n steps: skill.steps || [],\r\n inputs: skill.inputs || [],\r\n outputs: skill.outputs || [],\r\n toneAndRules: skill.toneAndRules || {},\r\n templates: skill.templates || [],\r\n scripts: skill.scripts || [],\r\n examples: skill.examples || [],\r\n relatedSkills: skill.relatedSkills || [],\r\n };\r\n }\r\n\r\n private static saveList(section: string, list: string[], skill: Partial<SkillInfo>): void {\r\n if (list.length === 0) return;\r\n\r\n if (section.includes('khi n\u00E0o') || section.includes('when')) {\r\n skill.whenToUse = list;\r\n } else if (section.includes('input')) {\r\n skill.inputs = list;\r\n } else if (section.includes('output')) {\r\n skill.outputs = list;\r\n } else if (section.includes('h\u1EA1n ch\u1EBF') || section.includes('limitation')) {\r\n skill.toneAndRules = skill.toneAndRules || {};\r\n skill.toneAndRules.limitations = list;\r\n } else if (section.includes('li\u00EAn k\u1EBFt') || section.includes('related')) {\r\n skill.relatedSkills = list;\r\n }\r\n }\r\n}\r\n\r\n", "/**\r\n * Skill Manager\r\n * Manages and discovers skills in a project\r\n */\r\nimport path from 'path';\r\nimport { FileSystemUtils } from '../../utils/file-system.js';\r\nimport { SkillParser, SkillInfo } from './skill-parser.js';\r\nimport { HERASPEC_DIR_NAME, SKILLS_DIR_NAME, PROJECT_TYPES, SKILLS } from '../config.js';\r\n\r\nexport class SkillManager {\r\n /**\r\n * Find skill path for a given project type and skill name\r\n */\r\n static async findSkillPath(\r\n projectType: string,\r\n skillName: string,\r\n projectPath: string = '.'\r\n ): Promise<string | null> {\r\n // Try project-specific skill first\r\n const projectSkillPath = path.join(\r\n projectPath,\r\n HERASPEC_DIR_NAME,\r\n SKILLS_DIR_NAME,\r\n projectType,\r\n skillName\r\n );\r\n\r\n if (await FileSystemUtils.fileExists(path.join(projectSkillPath, 'skill.md'))) {\r\n return projectSkillPath;\r\n }\r\n\r\n // Try cross-cutting skill\r\n const crossCuttingPath = path.join(\r\n projectPath,\r\n HERASPEC_DIR_NAME,\r\n SKILLS_DIR_NAME,\r\n skillName\r\n );\r\n\r\n if (await FileSystemUtils.fileExists(path.join(crossCuttingPath, 'skill.md'))) {\r\n return crossCuttingPath;\r\n }\r\n\r\n return null;\r\n }\r\n\r\n /**\r\n * Load skill information\r\n */\r\n static async loadSkill(\r\n projectType: string,\r\n skillName: string,\r\n projectPath: string = '.'\r\n ): Promise<SkillInfo | null> {\r\n const skillPath = await this.findSkillPath(projectType, skillName, projectPath);\r\n \r\n if (!skillPath) {\r\n return null;\r\n }\r\n\r\n try {\r\n return SkillParser.parseSkill(skillPath, skillName);\r\n } catch (error) {\r\n console.error(`Failed to load skill \"${skillName}\": ${error instanceof Error ? error.message : 'Unknown error'}`);\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * List all available skills\r\n */\r\n static async listSkills(projectPath: string = '.'): Promise<Array<{ projectType?: string; skillName: string; path: string }>> {\r\n const skillsDir = path.join(projectPath, HERASPEC_DIR_NAME, SKILLS_DIR_NAME);\r\n \r\n if (!(await FileSystemUtils.fileExists(skillsDir))) {\r\n return [];\r\n }\r\n\r\n const skills: Array<{ projectType?: string; skillName: string; path: string }> = [];\r\n const entries = await FileSystemUtils.readDirectory(skillsDir);\r\n\r\n for (const entry of entries) {\r\n const entryPath = path.join(skillsDir, entry);\r\n const stats = await FileSystemUtils.stat(entryPath);\r\n\r\n if (stats.isDirectory()) {\r\n // Check if it's a project type folder or cross-cutting skill\r\n const isProjectType = PROJECT_TYPES.includes(entry as any);\r\n \r\n if (isProjectType) {\r\n // It's a project type folder, list skills inside\r\n const projectSkills = await this.listSkillsInDirectory(entryPath, entry);\r\n skills.push(...projectSkills);\r\n } else {\r\n // It's a cross-cutting skill\r\n const skillMdPath = path.join(entryPath, 'skill.md');\r\n if (await FileSystemUtils.fileExists(skillMdPath)) {\r\n skills.push({\r\n skillName: entry,\r\n path: entryPath,\r\n });\r\n }\r\n }\r\n }\r\n }\r\n\r\n return skills;\r\n }\r\n\r\n /**\r\n * Extract skill from task line\r\n */\r\n static extractSkillFromTask(taskLine: string): { projectType?: string; skill?: string } | null {\r\n // Match: (projectType: xxx, skill: yyy)\r\n const match = taskLine.match(/\\(projectType:\\s*([^,)]+)(?:,\\s*skill:\\s*([^)]+))?\\)/i);\r\n \r\n if (match) {\r\n return {\r\n projectType: match[1]?.trim(),\r\n skill: match[2]?.trim(),\r\n };\r\n }\r\n\r\n // Match: (skill: yyy)\r\n const skillOnlyMatch = taskLine.match(/\\(skill:\\s*([^)]+)\\)/i);\r\n if (skillOnlyMatch) {\r\n return {\r\n skill: skillOnlyMatch[1]?.trim(),\r\n };\r\n }\r\n\r\n return null;\r\n }\r\n\r\n private static async listSkillsInDirectory(\r\n dir: string,\r\n projectType: string\r\n ): Promise<Array<{ projectType: string; skillName: string; path: string }>> {\r\n const skills: Array<{ projectType: string; skillName: string; path: string }> = [];\r\n const entries = await FileSystemUtils.readDirectory(dir);\r\n\r\n for (const entry of entries) {\r\n const entryPath = path.join(dir, entry);\r\n const stats = await FileSystemUtils.stat(entryPath);\r\n\r\n if (stats.isDirectory()) {\r\n const skillMdPath = path.join(entryPath, 'skill.md');\r\n if (await FileSystemUtils.fileExists(skillMdPath)) {\r\n skills.push({\r\n projectType,\r\n skillName: entry,\r\n path: entryPath,\r\n });\r\n }\r\n }\r\n }\r\n\r\n return skills;\r\n }\r\n}\r\n\r\n", "/**\r\n * Skills module exports\r\n */\r\nexport * from './skill-parser.js';\r\nexport * from './skill-manager.js';\r\n\r\n", "/**\r\n * HeraSpec Skill Command\r\n * Shows skill information, lists available skills, repairs, and adds skills\r\n */\r\nimport path from 'path';\r\nimport { readFileSync } from 'fs';\r\nimport chalk from 'chalk';\r\nimport ora from 'ora';\r\nimport { FileSystemUtils } from '../utils/file-system.js';\r\nimport { SkillManager, SkillParser } from '../core/skills/index.js';\r\nimport { HERASPEC_DIR_NAME, SKILLS_DIR_NAME, PROJECT_TYPES } from '../core/config.js';\r\nimport { getSkillTemplateInfo, getAllSkillTemplates } from '../core/templates/skills-template-map.js';\r\nimport { fileURLToPath } from 'url';\r\nimport { dirname, join } from 'path';\r\nimport { createRequire } from 'module';\r\n\r\nconst require = createRequire(import.meta.url);\r\nconst __filename = fileURLToPath(import.meta.url);\r\nconst __dirname = dirname(__filename);\r\n\r\n// Get HeraSpec core templates directory\r\n// Try multiple paths to handle both source and built versions, and installed packages\r\nasync function getCoreTemplatesDir(): Promise<string | null> {\r\n const possiblePaths: string[] = [];\r\n \r\n // Strategy 1: Resolve package.json from current file location (works when bundled)\r\n // When running from bin/heraspec.js, this resolves to the package root\r\n try {\r\n const packageJsonPath = require.resolve('../package.json');\r\n const packageDir = path.dirname(packageJsonPath);\r\n \r\n possiblePaths.push(\r\n join(packageDir, 'src', 'core', 'templates', 'skills'), // Source (when linked, this is the actual source)\r\n join(packageDir, 'dist', 'core', 'templates', 'skills'), // Built (templates copied during build)\r\n );\r\n } catch {\r\n // Could not resolve, continue\r\n }\r\n \r\n // Strategy 2: Try require.resolve('heraspec/package.json') for npm installed packages\r\n try {\r\n const packageJsonPath = require.resolve('heraspec/package.json');\r\n const packageDir = path.dirname(packageJsonPath);\r\n \r\n possiblePaths.push(\r\n join(packageDir, 'dist', 'core', 'templates', 'skills'), // Built\r\n join(packageDir, 'src', 'core', 'templates', 'skills'), // Source (if available)\r\n );\r\n } catch {\r\n // Package not found, continue\r\n }\r\n \r\n // Strategy 3: Relative paths from current file location (when running from source)\r\n possiblePaths.push(\r\n // Source version (for development) - when running from source: src/commands/skill.ts\r\n join(__dirname, '..', '..', 'src', 'core', 'templates', 'skills'),\r\n // Built version - when running from built: dist/commands/skill.js\r\n join(__dirname, '..', 'core', 'templates', 'skills'),\r\n // Alternative: from project root (when running from HeraSpec source)\r\n join(process.cwd(), 'src', 'core', 'templates', 'skills'),\r\n );\r\n\r\n for (const possiblePath of possiblePaths) {\r\n if (await FileSystemUtils.fileExists(possiblePath)) {\r\n return possiblePath;\r\n }\r\n }\r\n\r\n return null;\r\n}\r\n\r\nexport class SkillCommand {\r\n async list(projectPath: string = '.'): Promise<void> {\r\n const skills = await SkillManager.listSkills(projectPath);\r\n\r\n if (skills.length === 0) {\r\n console.log('No skills found. Skills will be created as needed.');\r\n console.log('See docs/SKILLS_STRUCTURE_PROPOSAL.md for skill structure.');\r\n return;\r\n }\r\n\r\n console.log('\\nAvailable Skills:\\n');\r\n console.log('\u2550'.repeat(60));\r\n\r\n // Group by project type\r\n const byProjectType: Record<string, Array<{ skillName: string; path: string }>> = {};\r\n const crossCutting: Array<{ skillName: string; path: string }> = [];\r\n\r\n for (const skill of skills) {\r\n if (skill.projectType) {\r\n if (!byProjectType[skill.projectType]) {\r\n byProjectType[skill.projectType] = [];\r\n }\r\n byProjectType[skill.projectType].push({\r\n skillName: skill.skillName,\r\n path: skill.path,\r\n });\r\n } else {\r\n crossCutting.push({\r\n skillName: skill.skillName,\r\n path: skill.path,\r\n });\r\n }\r\n }\r\n\r\n // Display project-specific skills\r\n for (const [projectType, projectSkills] of Object.entries(byProjectType)) {\r\n console.log(`\\n\uD83D\uDCE6 ${projectType}:`);\r\n for (const skill of projectSkills) {\r\n console.log(` \u2022 ${skill.skillName}`);\r\n }\r\n }\r\n\r\n // Display cross-cutting skills\r\n if (crossCutting.length > 0) {\r\n console.log(`\\n\uD83D\uDD27 Cross-cutting skills:`);\r\n for (const skill of crossCutting) {\r\n console.log(` \u2022 ${skill.skillName}`);\r\n }\r\n }\r\n\r\n console.log('\\n' + '\u2550'.repeat(60) + '\\n');\r\n }\r\n\r\n async show(skillName: string, projectType?: string, projectPath: string = '.'): Promise<void> {\r\n if (!skillName) {\r\n console.error('Error: Please specify a skill name');\r\n console.log('Usage: heraspec skill show <skill-name> [--project-type <type>]');\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n // Try to find skill\r\n let skillInfo = null;\r\n \r\n if (projectType) {\r\n skillInfo = await SkillManager.loadSkill(projectType, skillName, projectPath);\r\n } else {\r\n // Try to find in any project type\r\n const skills = await SkillManager.listSkills(projectPath);\r\n const found = skills.find(s => s.skillName === skillName);\r\n \r\n if (found) {\r\n try {\r\n skillInfo = SkillParser.parseSkill(found.path, skillName);\r\n } catch (error) {\r\n console.error(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\r\n process.exitCode = 1;\r\n return;\r\n }\r\n }\r\n }\r\n\r\n if (!skillInfo) {\r\n console.error(`Error: Skill \"${skillName}\" not found`);\r\n if (projectType) {\r\n console.log(`Searched in: heraspec/skills/${projectType}/${skillName}/`);\r\n } else {\r\n console.log('Searched in: heraspec/skills/');\r\n }\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n // Display skill information\r\n console.log(`\\n\uD83D\uDCDA Skill: ${skillInfo.name}\\n`);\r\n console.log('\u2550'.repeat(60));\r\n\r\n console.log(`\\n\uD83D\uDCCD Path: ${skillInfo.skillPath}\\n`);\r\n\r\n if (skillInfo.purpose) {\r\n console.log('## Purpose');\r\n console.log(skillInfo.purpose);\r\n console.log();\r\n }\r\n\r\n if (skillInfo.whenToUse.length > 0) {\r\n console.log('## When to Use');\r\n skillInfo.whenToUse.forEach(item => {\r\n console.log(`- ${item}`);\r\n });\r\n console.log();\r\n }\r\n\r\n if (skillInfo.steps.length > 0) {\r\n console.log('## Steps');\r\n skillInfo.steps.forEach((step, index) => {\r\n console.log(`${index + 1}. ${step}`);\r\n });\r\n console.log();\r\n }\r\n\r\n if (skillInfo.inputs.length > 0) {\r\n console.log('## Inputs');\r\n skillInfo.inputs.forEach(input => {\r\n console.log(`- ${input}`);\r\n });\r\n console.log();\r\n }\r\n\r\n if (skillInfo.outputs.length > 0) {\r\n console.log('## Outputs');\r\n skillInfo.outputs.forEach(output => {\r\n console.log(`- ${output}`);\r\n });\r\n console.log();\r\n }\r\n\r\n if (skillInfo.templates.length > 0) {\r\n console.log('## Available Templates');\r\n skillInfo.templates.forEach(template => {\r\n console.log(`- ${template}`);\r\n });\r\n console.log();\r\n }\r\n\r\n if (skillInfo.scripts.length > 0) {\r\n console.log('## Available Scripts');\r\n skillInfo.scripts.forEach(script => {\r\n console.log(`- ${script}`);\r\n });\r\n console.log();\r\n }\r\n\r\n if (skillInfo.toneAndRules.limitations && skillInfo.toneAndRules.limitations.length > 0) {\r\n console.log('## Limitations');\r\n skillInfo.toneAndRules.limitations.forEach(limitation => {\r\n console.log(`- ${limitation}`);\r\n });\r\n console.log();\r\n }\r\n\r\n // Show full skill.md content\r\n const skillMdPath = path.join(skillInfo.skillPath, 'skill.md');\r\n if (await FileSystemUtils.fileExists(skillMdPath)) {\r\n console.log('\u2550'.repeat(60));\r\n console.log('\\n## Full skill.md Content\\n');\r\n const content = await FileSystemUtils.readFile(skillMdPath);\r\n console.log(content);\r\n }\r\n\r\n console.log('\\n' + '\u2550'.repeat(60) + '\\n');\r\n }\r\n\r\n async repair(projectPath: string = '.'): Promise<void> {\r\n const spinner = ora('Repairing skills structure...').start();\r\n\r\n try {\r\n const skillsDir = path.join(projectPath, HERASPEC_DIR_NAME, SKILLS_DIR_NAME);\r\n \r\n if (!(await FileSystemUtils.fileExists(skillsDir))) {\r\n spinner.fail('Skills directory does not exist. Run \"heraspec init\" first.');\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n const skills = await SkillManager.listSkills(projectPath);\r\n let fixed = 0;\r\n let errors = 0;\r\n\r\n for (const skill of skills) {\r\n const skillPath = skill.path;\r\n const skillMdPath = path.join(skillPath, 'skill.md');\r\n\r\n // Ensure skill.md exists\r\n if (!(await FileSystemUtils.fileExists(skillMdPath))) {\r\n spinner.warn(`Missing skill.md in ${skillPath}`);\r\n errors++;\r\n continue;\r\n }\r\n\r\n // Ensure standard directories exist\r\n const standardDirs = ['templates', 'scripts', 'examples'];\r\n for (const dir of standardDirs) {\r\n const dirPath = path.join(skillPath, dir);\r\n if (!(await FileSystemUtils.fileExists(dirPath))) {\r\n await FileSystemUtils.createDirectory(dirPath);\r\n fixed++;\r\n }\r\n }\r\n\r\n // Validate skill.md structure (basic check)\r\n try {\r\n const content = await FileSystemUtils.readFile(skillMdPath);\r\n if (!content.includes('## Purpose') && !content.includes('# Skill:')) {\r\n spinner.warn(`Invalid skill.md structure in ${skillPath}`);\r\n }\r\n } catch (error) {\r\n spinner.warn(`Cannot read skill.md in ${skillPath}: ${error instanceof Error ? error.message : 'Unknown error'}`);\r\n errors++;\r\n }\r\n }\r\n\r\n if (errors === 0 && fixed === 0) {\r\n spinner.succeed('All skills are properly structured');\r\n } else {\r\n spinner.succeed(`Repaired ${fixed} issues, found ${errors} errors`);\r\n }\r\n } catch (error) {\r\n spinner.fail(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\r\n process.exitCode = 1;\r\n }\r\n }\r\n\r\n async add(skillName: string, projectType?: string, projectPath: string = '.'): Promise<void> {\r\n if (!skillName) {\r\n console.error('Error: Please specify a skill name');\r\n console.log('Usage: heraspec skills add <skill-name> [--project-type <type>]');\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n const spinner = ora(`Adding skill \"${skillName}\"...`).start();\r\n\r\n try {\r\n // Get template info\r\n const templateInfo = getSkillTemplateInfo(skillName, projectType);\r\n \r\n if (!templateInfo) {\r\n spinner.fail(`Skill template \"${skillName}\" not found`);\r\n console.log('\\nAvailable skills:');\r\n const allTemplates = getAllSkillTemplates();\r\n for (const { skillName: name, projectType: pt } of allTemplates) {\r\n if (pt) {\r\n console.log(` - ${name} (projectType: ${pt})`);\r\n } else {\r\n console.log(` - ${name} (cross-cutting)`);\r\n }\r\n }\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n // Determine destination path\r\n const skillsDir = path.join(projectPath, HERASPEC_DIR_NAME, SKILLS_DIR_NAME);\r\n \r\n let destPath: string;\r\n if (templateInfo.isCrossCutting) {\r\n destPath = path.join(skillsDir, skillName);\r\n } else {\r\n if (!templateInfo.projectType) {\r\n spinner.fail('Project type is required for this skill');\r\n process.exitCode = 1;\r\n return;\r\n }\r\n \r\n let effectiveSkillName = skillName;\r\n if (skillName.includes(':')) {\r\n const parts = skillName.split(':');\r\n if (parts.length === 2 && parts[0] === templateInfo.projectType) {\r\n effectiveSkillName = parts[1];\r\n }\r\n }\r\n \r\n destPath = path.join(skillsDir, templateInfo.projectType, effectiveSkillName);\r\n\r\n // Cleanup legacy prefixed folder if it exists (e.g., heraspec/skills/wordpress/wordpress:plugin-check)\r\n const legacyPath = path.join(skillsDir, templateInfo.projectType, `${templateInfo.projectType}:${effectiveSkillName}`);\r\n if (legacyPath !== destPath && await FileSystemUtils.fileExists(legacyPath)) {\r\n spinner.info(`Cleaning up legacy prefixed skill folder: ${legacyPath}`);\r\n try {\r\n await FileSystemUtils.removeDirectory(legacyPath, true);\r\n } catch (cleanupError) {\r\n spinner.warn(`Could not remove legacy folder ${legacyPath}: ${cleanupError instanceof Error ? cleanupError.message : 'Unknown error'}`);\r\n }\r\n }\r\n }\r\n\r\n // Check if already exists - remove old skill before adding new one\r\n const isUpdate = await FileSystemUtils.fileExists(destPath);\r\n if (isUpdate) {\r\n spinner.info(`Skill \"${skillName}\" already exists at ${destPath}`);\r\n spinner.start(`Removing old version to update with latest...`);\r\n try {\r\n await FileSystemUtils.removeDirectory(destPath, true);\r\n spinner.succeed(`Removed old skill \"${skillName}\"`);\r\n } catch (error) {\r\n spinner.fail(`Failed to remove old skill: ${error instanceof Error ? error.message : 'Unknown error'}`);\r\n process.exitCode = 1;\r\n return;\r\n }\r\n spinner.start(`Adding updated skill \"${skillName}\"...`);\r\n }\r\n\r\n // Ensure directories exist\r\n await FileSystemUtils.createDirectory(destPath);\r\n\r\n // Get core templates directory\r\n const coreTemplatesDir = await getCoreTemplatesDir();\r\n if (!coreTemplatesDir) {\r\n spinner.fail('Cannot find HeraSpec templates directory. Make sure you are running from HeraSpec project or have templates installed.');\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n const templateFile = path.join(coreTemplatesDir, templateInfo.templateFileName);\r\n\r\n // Check if template file exists\r\n if (!(await FileSystemUtils.fileExists(templateFile))) {\r\n spinner.fail(`Template file not found: ${templateFile}`);\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n await FileSystemUtils.copyFile(templateFile, path.join(destPath, 'skill.md'));\r\n\r\n // Copy Vietnamese translation file if specified\r\n if (templateInfo.viFileName) {\r\n const viFile = path.join(coreTemplatesDir, templateInfo.viFileName);\r\n if (await FileSystemUtils.fileExists(viFile)) {\r\n await FileSystemUtils.copyFile(viFile, path.join(destPath, 'skill.vi.md'));\r\n }\r\n }\r\n\r\n // Copy resource directories if specified\r\n if (templateInfo.resourceDirs) {\r\n for (const resourceDir of templateInfo.resourceDirs) {\r\n const srcResourceDir = path.join(coreTemplatesDir, resourceDir);\r\n const destResourceDir = path.join(destPath, resourceDir);\r\n \r\n if (await FileSystemUtils.fileExists(srcResourceDir)) {\r\n await FileSystemUtils.copyDirectory(srcResourceDir, destResourceDir);\r\n }\r\n }\r\n }\r\n\r\n // Create standard directories\r\n await FileSystemUtils.createDirectory(path.join(destPath, 'templates'));\r\n await FileSystemUtils.createDirectory(path.join(destPath, 'scripts'));\r\n await FileSystemUtils.createDirectory(path.join(destPath, 'examples'));\r\n\r\n const successMessage = isUpdate \r\n ? `Skill \"${skillName}\" updated successfully`\r\n : `Skill \"${skillName}\" added successfully`;\r\n \r\n spinner.succeed(successMessage);\r\n console.log(`\\n\uD83D\uDCCD Location: ${destPath}`);\r\n if (isUpdate) {\r\n console.log(`\\n\u2728 Skill has been updated with latest features and improvements.`);\r\n }\r\n console.log(`\\n\uD83D\uDCA1 Run \"heraspec skill show ${skillName}${projectType ? ` --project-type ${projectType}` : ''}\" to view details\\n`);\r\n } catch (error) {\r\n spinner.fail(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\r\n process.exitCode = 1;\r\n }\r\n }\r\n\r\n async update(skillName: string, projectType?: string, projectPath: string = '.'): Promise<void> {\r\n // The internal logic of add already handles updating existing skills by removing the old version first\r\n return this.add(skillName, projectType, projectPath);\r\n }\r\n}\r\n", "/**\r\n * HeraSpec CLI Entry Point\r\n */\r\nimport { Command } from 'commander';\r\nimport { createRequire } from 'module';\r\nimport { fileURLToPath } from 'url';\r\nimport { dirname, join } from 'path';\r\nimport { InitCommand } from '../core/init.js';\r\nimport { ListCommand } from '../core/list.js';\r\nimport { ArchiveCommand } from '../core/archive.js';\r\nimport { SyncCommand } from '../core/sync.js';\r\nimport { RestoreCommand } from '../core/restore.js';\r\nimport { ShowCommand } from '../commands/show.js';\r\nimport { ValidateCommand } from '../commands/validate.js';\r\nimport { SkillCommand } from '../commands/skill.js';\r\nimport { HelperCommand } from '../commands/helper.js';\r\nimport { MakeDocsCommand } from '../commands/make-docs.js';\r\nimport { MakeTestCommand } from '../commands/make-test.js';\r\nimport { MakeCodeCommand } from '../commands/make-code.js';\r\nimport { SuggestCommand } from '../commands/suggest.js';\r\nimport { MemoryCommand } from '../commands/memory.js';\r\nimport { HotfixCommand } from '../commands/hotfix.js';\r\nimport { ExploreCommand } from '../commands/explore.js';\r\n\r\nconst require = createRequire(import.meta.url);\r\n\r\n// Get package.json path relative to the built file location\r\nconst __filename = fileURLToPath(import.meta.url);\r\nconst __dirname = dirname(__filename);\r\nconst packageJsonPath = join(__dirname, '..', 'package.json');\r\nconst { version } = require(packageJsonPath);\r\n\r\nconst program = new Command();\r\n\r\nprogram\r\n .name('heraspec')\r\n .description('Universal spec-first development framework + CLI')\r\n .version(version);\r\n\r\nprogram\r\n .command('init [path]')\r\n .description('Initialize HeraSpec in your project')\r\n .action(async (targetPath = '.') => {\r\n try {\r\n const initCommand = new InitCommand();\r\n await initCommand.execute(targetPath);\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nprogram\r\n .command('list')\r\n .description('List items (changes by default). Use --specs to list specs.')\r\n .option('--specs', 'List specs instead of changes')\r\n .option('--changes', 'List changes explicitly (default)')\r\n .action(async (options?: { specs?: boolean; changes?: boolean }) => {\r\n try {\r\n const listCommand = new ListCommand();\r\n const mode: 'changes' | 'specs' = options?.specs ? 'specs' : 'changes';\r\n await listCommand.execute('.', mode);\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nprogram\r\n .command('show [item-name]')\r\n .description('Show a change or spec')\r\n .action(async (itemName?: string) => {\r\n try {\r\n const showCommand = new ShowCommand();\r\n await showCommand.execute(itemName);\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nprogram\r\n .command('validate [item-name]')\r\n .description('Validate a change or spec')\r\n .option('--strict', 'Enable strict validation mode')\r\n .action(async (itemName?: string, options?: { strict?: boolean }) => {\r\n try {\r\n const validateCommand = new ValidateCommand();\r\n await validateCommand.execute(itemName, options);\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nprogram\r\n .command('archive [change-name]')\r\n .description('Archive a completed change and update main specs')\r\n .option('-y, --yes', 'Skip confirmation prompts')\r\n .action(async (changeName?: string, options?: { yes?: boolean }) => {\r\n try {\r\n const archiveCommand = new ArchiveCommand();\r\n await archiveCommand.execute(changeName, options);\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nprogram\r\n .command('sync [change-name]')\r\n .description('Sync a change with its source specs to resolve parallel merge conflicts')\r\n .action(async (changeName?: string) => {\r\n try {\r\n const syncCommand = new SyncCommand();\r\n await syncCommand.execute(changeName);\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nprogram\r\n .command('restore [archive-name]')\r\n .description('Restore an archived change back to active changes')\r\n .option('-y, --yes', 'Skip confirmation prompts')\r\n .action(async (archiveName?: string, options?: { yes?: boolean }) => {\r\n try {\r\n const restoreCommand = new RestoreCommand();\r\n await restoreCommand.execute(archiveName, options);\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nprogram\r\n .command('view')\r\n .description('Display an interactive dashboard of specs and changes')\r\n .action(async () => {\r\n try {\r\n const listCommand = new ListCommand();\r\n console.log('\\n\uD83D\uDCCA HeraSpec Dashboard\\n');\r\n console.log('\u2550'.repeat(60));\r\n await listCommand.execute('.', 'changes');\r\n await listCommand.execute('.', 'specs');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nprogram\r\n .command('skills')\r\n .description('List all available skills (shortcut for skill list)')\r\n .action(async () => {\r\n try {\r\n const skillCommand = new SkillCommand();\r\n await skillCommand.list('.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nprogram\r\n .command('helper')\r\n .description('Show usage guide, example prompts, and workflow instructions')\r\n .action(async () => {\r\n try {\r\n const helperCommand = new HelperCommand();\r\n await helperCommand.execute();\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\n// Make commands\r\nconst makeCmd = program\r\n .command('make')\r\n .description('Generate project artifacts');\r\n\r\nmakeCmd\r\n .command('docs')\r\n .description('Generate project documentation from specs')\r\n .option('--agent <agent>', 'Specify AI agent for documentation (default: chatgpt)', 'chatgpt')\r\n .action(async (options?: { agent?: string }) => {\r\n try {\r\n const makeDocsCommand = new MakeDocsCommand();\r\n await makeDocsCommand.execute('.', options?.agent || 'chatgpt');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nmakeCmd\r\n .command('test')\r\n .description('Generate test cases from specs')\r\n .option('--type <type>', 'Test type: unit, integration, e2e (default: unit)', 'unit')\r\n .action(async (options?: { type?: string }) => {\r\n try {\r\n const makeTestCommand = new MakeTestCommand();\r\n await makeTestCommand.execute('.', options?.type || 'unit');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nmakeCmd\r\n .command('code')\r\n .description('Generate code skeletons from specs')\r\n .argument('[spec-name]', 'Specific spec to generate code for (optional)')\r\n .action(async (specName?: string) => {\r\n try {\r\n const makeCodeCommand = new MakeCodeCommand();\r\n await makeCodeCommand.execute('.', specName);\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nprogram\r\n .command('suggest')\r\n .description('Analyze project and suggest new features')\r\n .action(async () => {\r\n try {\r\n const suggestCommand = new SuggestCommand();\r\n await suggestCommand.execute('.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\n// Skill commands\r\nconst skillCmd = program\r\n .command('skill')\r\n .description('Manage and view skills');\r\n\r\nskillCmd\r\n .command('list')\r\n .description('List all available skills')\r\n .action(async () => {\r\n try {\r\n const skillCommand = new SkillCommand();\r\n await skillCommand.list('.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nskillCmd\r\n .command('show <skill-name>')\r\n .description('Show detailed information about a skill')\r\n .option('--project-type <type>', 'Specify project type for project-specific skills')\r\n .action(async (skillName: string, options?: { projectType?: string }) => {\r\n try {\r\n const skillCommand = new SkillCommand();\r\n await skillCommand.show(skillName, options?.projectType, '.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nskillCmd\r\n .command('repair')\r\n .description('Repair skills structure to match HeraSpec standards')\r\n .action(async () => {\r\n try {\r\n const skillCommand = new SkillCommand();\r\n await skillCommand.repair('.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nskillCmd\r\n .command('add <skill-name>')\r\n .description('Add a default skill to the project from HeraSpec templates')\r\n .option('--project-type <type>', 'Specify project type for project-specific skills')\r\n .action(async (skillName: string, options?: { projectType?: string }) => {\r\n try {\r\n const skillCommand = new SkillCommand();\r\n await skillCommand.add(skillName, options?.projectType, '.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nskillCmd\r\n .command('update <skill-name>')\r\n .description('Update an existing skill with the latest from HeraSpec templates')\r\n .option('--project-type <type>', 'Specify project type for project-specific skills')\r\n .action(async (skillName: string, options?: { projectType?: string }) => {\r\n try {\r\n const skillCommand = new SkillCommand();\r\n await skillCommand.update(skillName, options?.projectType, '.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nprogram\r\n .command('hotfix <title>')\r\n .description('Fast-track shortcut to log a bugfix directly to memory')\r\n .option('-n, --narrative <text>', 'Describe the fix (narrative)')\r\n .action(async (title: string, options: any) => {\r\n try {\r\n const hotfixCommand = new HotfixCommand();\r\n await hotfixCommand.execute(title, options, '.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\n// Memory commands\r\nconst memoryCmd = program\r\n .command('memory')\r\n .description('Project memory management (observations, context, search)');\r\n\r\nmemoryCmd\r\n .command('log')\r\n .description('Record an observation (decision, bugfix, feature, etc.)')\r\n .requiredOption('--type <type>', 'Observation type: decision, bugfix, feature, refactor, discovery, change')\r\n .requiredOption('--title <title>', 'Short title for the observation')\r\n .option('--narrative <text>', 'Detailed description')\r\n .option('--concepts <tags>', 'Comma-separated concept tags')\r\n .option('--files-modified <files>', 'Comma-separated file paths modified')\r\n .option('--files-read <files>', 'Comma-separated file paths read')\r\n .option('--discovery-tokens <n>', 'Estimated tokens spent exploring/searching before logging this observation')\r\n .option('--session-id <id>', 'Session identifier')\r\n .option('--project <name>', 'Project name')\r\n .action(async (options: any) => {\r\n try {\r\n const memoryCommand = new MemoryCommand();\r\n await memoryCommand.log(options, '.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nmemoryCmd\r\n .command('query <question>')\r\n .description('Search observations using semantic vector embeddings')\r\n .option('--limit <n>', 'Max results', '10')\r\n .option('--project <name>', 'Filter by project')\r\n .action(async (question: string, options: any) => {\r\n try {\r\n const memoryCommand = new MemoryCommand();\r\n await memoryCommand.query(question, { limit: parseInt(options.limit), project: options.project }, '.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nmemoryCmd\r\n .command('search [query]')\r\n .description('Search observations using full-text search')\r\n .option('--type <type>', 'Filter by observation type')\r\n .option('--concepts <tags>', 'Filter by concept tags')\r\n .option('--files <files>', 'Filter by file paths')\r\n .option('--limit <n>', 'Max results', '20')\r\n .option('--id <id>', 'Show full details of a specific observation')\r\n .option('--project <name>', 'Filter by project')\r\n .action(async (query: string | undefined, options: any) => {\r\n try {\r\n const memoryCommand = new MemoryCommand();\r\n await memoryCommand.search(query || '', { ...options, limit: parseInt(options.limit), id: options.id ? parseInt(options.id) : undefined }, '.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nmemoryCmd\r\n .command('context')\r\n .description('Generate context markdown for AI agent sessions')\r\n .option('--output <mode>', 'Output: stdout (default) or file', 'stdout')\r\n .option('--max-tokens <n>', 'Token budget')\r\n .action(async (options: any) => {\r\n try {\r\n const memoryCommand = new MemoryCommand();\r\n await memoryCommand.context({ output: options.output, maxTokens: options.maxTokens ? parseInt(options.maxTokens) : undefined }, '.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nmemoryCmd\r\n .command('summarize')\r\n .description('Create a session summary')\r\n .requiredOption('--request <text>', 'What the user asked for')\r\n .option('--investigated <text>', 'What was investigated/researched')\r\n .option('--learned <text>', 'What was learned')\r\n .option('--completed <text>', 'What was completed')\r\n .option('--next-steps <text>', 'What remains to be done')\r\n .option('--files-read <files>', 'Comma-separated files read')\r\n .option('--files-edited <files>', 'Comma-separated files edited')\r\n .option('--session-id <id>', 'Session identifier')\r\n .option('--project <name>', 'Project name')\r\n .action(async (options: any) => {\r\n try {\r\n const memoryCommand = new MemoryCommand();\r\n await memoryCommand.summarize(options, '.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nmemoryCmd\r\n .command('status')\r\n .description('Show memory statistics')\r\n .action(async () => {\r\n try {\r\n const memoryCommand = new MemoryCommand();\r\n await memoryCommand.status('.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nmemoryCmd\r\n .command('timeline')\r\n .description('Show observation timeline')\r\n .option('--limit <n>', 'Max items', '20')\r\n .option('--project <name>', 'Filter by project')\r\n .action(async (options: any) => {\r\n try {\r\n const memoryCommand = new MemoryCommand();\r\n await memoryCommand.timeline({ limit: parseInt(options.limit), project: options.project }, '.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nmemoryCmd\r\n .command('prune <days>')\r\n .description('Delete observations older than N days')\r\n .option('--project <name>', 'Filter by project')\r\n .action(async (days: string, options: any) => {\r\n try {\r\n const memoryCommand = new MemoryCommand();\r\n await memoryCommand.prune(parseInt(days), options, '.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nmemoryCmd\r\n .command('optimize')\r\n .description('Auto-detect project scale and recommend optimal config')\r\n .option('--yes', 'Apply changes without confirmation')\r\n .action(async (options: any) => {\r\n try {\r\n const memoryCommand = new MemoryCommand();\r\n await memoryCommand.optimize({ yes: options.yes }, '.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nmemoryCmd\r\n .command('bootstrap')\r\n .description('Import historical specs and archives into memory')\r\n .option('--yes', 'Apply changes without confirmation')\r\n .action(async (options: any) => {\r\n try {\r\n const memoryCommand = new MemoryCommand();\r\n await memoryCommand.bootstrap({ yes: options.yes }, '.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nmemoryCmd\r\n .command('analytics')\r\n .description('Show token usage and economic savings metrics')\r\n .option('-H, --history', 'Show 13 most recent database size history logs')\r\n .action(async (options: any) => {\r\n try {\r\n const memoryCommand = new MemoryCommand();\r\n await memoryCommand.analytics({ history: options.history }, '.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nmemoryCmd\r\n .command('index')\r\n .description('Scan project and generate architecture map observation')\r\n .option('--depth <n>', 'Maximum directory depth to scan (default: 3)')\r\n .option('--yes', 'Apply changes without confirmation')\r\n .action(async (options: any) => {\r\n try {\r\n const memoryCommand = new MemoryCommand();\r\n await memoryCommand.index({ depth: options.depth, yes: options.yes }, '.');\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\n// Explore commands\r\nconst exploreCmd = program\r\n .command('explore')\r\n .description('Smart code exploration (token-efficient)');\r\n\r\nexploreCmd\r\n .command('outline <file>')\r\n .description('Show structural skeleton of a file (functions, classes, exports)')\r\n .action(async (filePath: string) => {\r\n try {\r\n const exploreCommand = new ExploreCommand();\r\n await exploreCommand.outline(filePath);\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nexploreCmd\r\n .command('search <query> [path]')\r\n .description('Search for symbols across the codebase')\r\n .option('--limit <n>', 'Max results', '20')\r\n .action(async (query: string, searchPath: string | undefined, options: any) => {\r\n try {\r\n const exploreCommand = new ExploreCommand();\r\n await exploreCommand.search(query, searchPath || '.', { limit: parseInt(options.limit) });\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nexploreCmd\r\n .command('unfold <file> <symbol>')\r\n .description('Show full implementation of a specific symbol')\r\n .action(async (filePath: string, symbolName: string) => {\r\n try {\r\n const exploreCommand = new ExploreCommand();\r\n await exploreCommand.unfold(filePath, symbolName);\r\n } catch (error) {\r\n console.error(`Error: ${(error as Error).message}`);\r\n process.exit(1);\r\n }\r\n });\r\n\r\nprogram.parse();\r\n\r\n", "/**\r\n * HeraSpec Init Command\r\n * Initializes HeraSpec in a project\r\n */\r\nimport ora from 'ora';\r\nimport chalk from 'chalk';\r\nimport path from 'path';\r\nimport { FileSystemUtils } from '../utils/file-system.js';\r\nimport { TemplateManager } from './templates/index.js';\r\nimport {\r\n HERASPEC_DIR_NAME,\r\n SPECS_DIR_NAME,\r\n CHANGES_DIR_NAME,\r\n ARCHIVES_DIR_NAME,\r\n SKILLS_DIR_NAME,\r\n KNOWLEDGE_DIR_NAME,\r\n HERASPEC_MARKERS,\r\n} from './config.js';\r\nimport { getSkillTemplateInfo, getAllSkillTemplates } from './templates/skills-template-map.js';\r\nimport { MemoryCommand } from '../commands/memory.js';\r\nimport { fileURLToPath } from 'url';\r\nimport { dirname, join } from 'path';\r\nimport { createRequire } from 'module';\r\n\r\nconst require = createRequire(import.meta.url);\r\nconst __filename = fileURLToPath(import.meta.url);\r\nconst __dirname = dirname(__filename);\r\n\r\nexport class InitCommand {\r\n async execute(targetPath: string = '.'): Promise<void> {\r\n const resolvedPath = path.resolve(targetPath);\r\n const heraspecPath = path.join(resolvedPath, HERASPEC_DIR_NAME);\r\n\r\n // Check if already initialized\r\n const alreadyInitialized = await FileSystemUtils.fileExists(\r\n path.join(heraspecPath, HERASPEC_MARKERS.PROJECT_MD)\r\n );\r\n\r\n const spinner = ora({\r\n text: alreadyInitialized ? 'Updating HeraSpec...' : 'Initializing HeraSpec...',\r\n color: 'blue',\r\n }).start();\r\n\r\n try {\r\n // Create directory structure\r\n await FileSystemUtils.createDirectory(heraspecPath);\r\n await FileSystemUtils.createDirectory(path.join(heraspecPath, SPECS_DIR_NAME));\r\n await FileSystemUtils.createDirectory(path.join(heraspecPath, CHANGES_DIR_NAME));\r\n await FileSystemUtils.createDirectory(path.join(heraspecPath, ARCHIVES_DIR_NAME));\r\n await FileSystemUtils.createDirectory(path.join(heraspecPath, SKILLS_DIR_NAME));\r\n await FileSystemUtils.createDirectory(path.join(heraspecPath, KNOWLEDGE_DIR_NAME));\r\n\r\n // Create skills README\r\n const skillsReadmePath = path.join(heraspecPath, SKILLS_DIR_NAME, 'README.md');\r\n if (!(await FileSystemUtils.fileExists(skillsReadmePath))) {\r\n const skillsReadme = await this.getSkillsReadmeTemplate();\r\n await FileSystemUtils.writeFile(skillsReadmePath, skillsReadme);\r\n }\r\n\r\n // Create UI/UX skill quick reference guide\r\n const uiuxGuidePath = path.join(heraspecPath, SKILLS_DIR_NAME, 'UI_UX_SKILL_QUICK_REFERENCE.md');\r\n if (!(await FileSystemUtils.fileExists(uiuxGuidePath))) {\r\n const uiuxGuide = await this.getUIUXQuickReference();\r\n await FileSystemUtils.writeFile(uiuxGuidePath, uiuxGuide);\r\n }\r\n\r\n // Deploy/update knowledge base (built-in only, preserves custom/)\r\n await this.deployKnowledge(heraspecPath);\r\n\r\n // Create template files\r\n await this.createTemplateFiles(heraspecPath, alreadyInitialized);\r\n\r\n // Migration: Check for AGENTS.md and rename it to AGENTS.heraspec.md\r\n const legacyAgentsPath = path.join(resolvedPath, 'AGENTS.md');\r\n const newAgentsPath = path.join(resolvedPath, HERASPEC_MARKERS.AGENTS_MD);\r\n \r\n if (await FileSystemUtils.fileExists(legacyAgentsPath) && !(await FileSystemUtils.fileExists(newAgentsPath))) {\r\n await FileSystemUtils.moveFile(legacyAgentsPath, newAgentsPath);\r\n }\r\n\r\n // Create or update root AGENTS.md (merge Skills section if exists)\r\n await this.updateAgentsFile(newAgentsPath, alreadyInitialized);\r\n\r\n // Update installed built-in skills (only on re-init, skip custom project skills)\r\n if (alreadyInitialized) {\r\n await this.updateInstalledSkills(heraspecPath);\r\n }\r\n\r\n // For all projects (new or existing), ensure project-memory is installed and check for history\r\n await this.checkAndBootstrapMemory(heraspecPath, resolvedPath, spinner);\r\n\r\n // Update related markdown files (README.md, etc.)\r\n await this.updateRelatedMarkdownFiles(resolvedPath);\r\n\r\n spinner.stop();\r\n\r\n // Automate Memory Indexing and Context Generation\r\n try {\r\n const memoryCommand = new MemoryCommand();\r\n await memoryCommand.index({ depth: \"3\", yes: true }, resolvedPath);\r\n await memoryCommand.context({ output: 'file' }, resolvedPath);\r\n } catch (err) {\r\n // Silently continue if something goes wrong\r\n }\r\n\r\n console.log();\r\n console.log(\r\n chalk.green(\r\n alreadyInitialized\r\n ? '\u2714 HeraSpec updated successfully'\r\n : '\u2714 HeraSpec initialized successfully'\r\n )\r\n );\r\n\r\n console.log();\r\n console.log(chalk.cyan('Next steps:'));\r\n console.log(\r\n chalk.gray('1. Review and update heraspec/project.md with your project details')\r\n );\r\n console.log(\r\n chalk.gray('2. Create your first change: \"Create a HeraSpec change to...\"')\r\n );\r\n console.log(\r\n chalk.gray('3. List changes: heraspec list')\r\n );\r\n } catch (error) {\r\n spinner.fail(chalk.red(`Error: ${(error as Error).message}`));\r\n throw error;\r\n }\r\n }\r\n\r\n private async createTemplateFiles(\r\n heraspecPath: string,\r\n skipExisting: boolean\r\n ): Promise<void> {\r\n const projectMdPath = path.join(heraspecPath, HERASPEC_MARKERS.PROJECT_MD);\r\n const configYamlPath = path.join(heraspecPath, HERASPEC_MARKERS.CONFIG_YAML);\r\n const newProjectTemplate = TemplateManager.getProjectTemplate();\r\n\r\n // Handle project.md with smart merge\r\n const projectExists = await FileSystemUtils.fileExists(projectMdPath);\r\n\r\n if (!projectExists) {\r\n // New project \u2014 write fresh template\r\n await FileSystemUtils.writeFile(projectMdPath, newProjectTemplate);\r\n } else if (skipExisting) {\r\n // Re-init: check if template has new content that existing file doesn't have\r\n const existingContent = await FileSystemUtils.readFile(projectMdPath);\r\n const hasChanges = this.detectTemplateChanges(existingContent, newProjectTemplate);\r\n\r\n if (hasChanges) {\r\n // Create numbered backup\r\n const backupPath = await this.createNumberedBackup(projectMdPath, heraspecPath);\r\n const backupName = path.basename(backupPath);\r\n\r\n // Write merged content: new template sections + merge reference\r\n const mergedContent = this.buildMergedProjectMd(existingContent, newProjectTemplate, backupName);\r\n await FileSystemUtils.writeFile(projectMdPath, mergedContent);\r\n }\r\n // else: no template changes, keep existing file as-is\r\n } else {\r\n // First init but file somehow exists (edge case) \u2014 overwrite\r\n await FileSystemUtils.writeFile(projectMdPath, newProjectTemplate);\r\n }\r\n\r\n // Create config.yaml (only if not exists)\r\n if (!(await FileSystemUtils.fileExists(configYamlPath))) {\r\n if (projectExists) {\r\n await this.migrateLegacyProjectMd(projectMdPath, configYamlPath);\r\n } else {\r\n await FileSystemUtils.writeFile(\r\n configYamlPath,\r\n TemplateManager.getConfigTemplate()\r\n );\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Migrate legacy project.md (extract technical configs to config.yaml)\r\n */\r\n private async migrateLegacyProjectMd(projectMdPath: string, configYamlPath: string): Promise<void> {\r\n const content = await FileSystemUtils.readFile(projectMdPath);\r\n let newYaml = `projectType: generic-webapp\\nprojectName: \"HeraSpec Project\"\\ndescription: \"A new project using HeraSpec\"\\nskills: []\\n`;\r\n \r\n // Attempt to extract project type\r\n const projectTypeMatch = content.match(/## Project Types\\\\s*\\\\n\\\\s*-\\\\s*([a-zA-Z0-9-]+)/);\r\n if (projectTypeMatch && projectTypeMatch[1]) {\r\n newYaml = newYaml.replace(/projectType:.*/, `projectType: ${projectTypeMatch[1]}`);\r\n }\r\n\r\n // Try to extract tech stack\r\n const stackMatch = content.match(/## Tech Stack\\\\s*\\\\n([^#]+)/);\r\n if (stackMatch && stackMatch[1]) {\r\n const stackItems = stackMatch[1].split('\\\\n')\r\n .filter(line => line.trim().startsWith('-'))\r\n .map(line => line.replace('-', '').trim());\r\n if (stackItems.length > 0) {\r\n newYaml += `techStack:\\n` + stackItems.map(item => ` - \"${item}\"`).join('\\n') + '\\n';\r\n }\r\n }\r\n\r\n await FileSystemUtils.writeFile(configYamlPath, newYaml);\r\n \r\n // Optionally clean up project.md by removing Project Types and Tech Stack\r\n let updatedMd = content;\r\n updatedMd = updatedMd.replace(/## Project Types[\\\\s\\\\S]*?(?=##|$)/, '');\r\n updatedMd = updatedMd.replace(/## Tech Stack[\\\\s\\\\S]*?(?=##|$)/, '');\r\n \r\n // Also add a migration note at top if not present\r\n if (!updatedMd.includes('<!-- HeraSpec Update: Migrated config to config.yaml -->')) {\r\n updatedMd = `<!-- HeraSpec Update: Migrated config to config.yaml -->\\n` + updatedMd.trimStart();\r\n }\r\n await FileSystemUtils.writeFile(projectMdPath, updatedMd);\r\n }\r\n\r\n /**\r\n * Detect if the new template has sections that the existing file lacks\r\n */\r\n private detectTemplateChanges(existingContent: string, newTemplate: string): boolean {\r\n // Extract ## section headers from both\r\n const sectionRegex = /^## .+$/gm;\r\n const existingSections = new Set(\r\n (existingContent.match(sectionRegex) || []).map(s => s.trim().toLowerCase())\r\n );\r\n const newSections = (newTemplate.match(sectionRegex) || []).map(s => s.trim().toLowerCase());\r\n\r\n // Check if any new section is missing from existing\r\n for (const section of newSections) {\r\n if (!existingSections.has(section)) {\r\n return true; // New section found\r\n }\r\n }\r\n\r\n return false;\r\n }\r\n\r\n /**\r\n * Create numbered backup: project.back1.md, project.back2.md, etc.\r\n */\r\n private async createNumberedBackup(filePath: string, dirPath: string): Promise<string> {\r\n const ext = path.extname(filePath);\r\n const base = path.basename(filePath, ext);\r\n let backupNumber = 1;\r\n\r\n while (true) {\r\n const backupPath = path.join(dirPath, `${base}.back${backupNumber}${ext}`);\r\n if (!(await FileSystemUtils.fileExists(backupPath))) {\r\n // Copy existing file to backup\r\n await FileSystemUtils.copyFile(filePath, backupPath);\r\n return backupPath;\r\n }\r\n backupNumber++;\r\n if (backupNumber > 99) break; // Safety limit\r\n }\r\n\r\n // Fallback: overwrite last backup\r\n const fallbackPath = path.join(dirPath, `${base}.back99${ext}`);\r\n await FileSystemUtils.copyFile(filePath, fallbackPath);\r\n return fallbackPath;\r\n }\r\n\r\n /**\r\n * Build merged project.md:\r\n * - Keeps all existing user content (descriptions, tech stack, conventions)\r\n * - Adds any NEW sections from the template that don't exist yet\r\n * - Adds a merge note at the top referencing the backup\r\n */\r\n private buildMergedProjectMd(\r\n existingContent: string,\r\n newTemplate: string,\r\n backupFileName: string\r\n ): string {\r\n // Parse sections from both files\r\n const existingSections = this.parseSections(existingContent);\r\n const templateSections = this.parseSections(newTemplate);\r\n\r\n // Build merged content: existing sections take priority, new sections are appended\r\n const mergedParts: string[] = [];\r\n const existingSectionHeaders = new Set(\r\n existingSections.map(s => s.header.trim().toLowerCase())\r\n );\r\n\r\n // 1. Add merge notice at top\r\n const mergeNote = `<!-- HeraSpec Update: Template updated. Previous version backed up to \"${backupFileName}\". New sections (if any) have been appended below. -->\\n`;\r\n mergedParts.push(mergeNote);\r\n\r\n // 2. Keep all existing content intact\r\n mergedParts.push(existingContent.trimEnd());\r\n\r\n // 3. Append any NEW sections from template that don't exist in current file\r\n const newSections: { header: string; content: string }[] = [];\r\n for (const section of templateSections) {\r\n if (!existingSectionHeaders.has(section.header.trim().toLowerCase())) {\r\n newSections.push(section);\r\n }\r\n }\r\n\r\n if (newSections.length > 0) {\r\n mergedParts.push('\\n\\n<!-- New sections added by HeraSpec update -->');\r\n for (const section of newSections) {\r\n mergedParts.push(`\\n${section.header}\\n${section.content.trimEnd()}`);\r\n }\r\n }\r\n\r\n return mergedParts.join('\\n').trimEnd() + '\\n';\r\n }\r\n\r\n /**\r\n * Parse markdown sections (## headers) from content\r\n */\r\n private parseSections(content: string): { header: string; content: string }[] {\r\n const sections: { header: string; content: string }[] = [];\r\n const lines = content.split('\\n');\r\n let currentHeader = '';\r\n let currentContent: string[] = [];\r\n\r\n for (const line of lines) {\r\n if (line.match(/^## /)) {\r\n // Save previous section\r\n if (currentHeader) {\r\n sections.push({ header: currentHeader, content: currentContent.join('\\n') });\r\n }\r\n currentHeader = line;\r\n currentContent = [];\r\n } else if (currentHeader) {\r\n currentContent.push(line);\r\n }\r\n }\r\n\r\n // Save last section\r\n if (currentHeader) {\r\n sections.push({ header: currentHeader, content: currentContent.join('\\n') });\r\n }\r\n\r\n return sections;\r\n }\r\n\r\n private async updateAgentsFile(agentsPath: string, alreadyInitialized: boolean): Promise<void> {\r\n const skillsSectionMarker = '## Skills System';\r\n\r\n if (!alreadyInitialized) {\r\n // New project: create full template\r\n await FileSystemUtils.writeFile(\r\n agentsPath,\r\n TemplateManager.getAgentsTemplate()\r\n );\r\n return;\r\n }\r\n\r\n // Existing project: merge or overwrite Skills section to ensure latest rules are applied\r\n let existingContent = '';\r\n if (await FileSystemUtils.fileExists(agentsPath)) {\r\n existingContent = await FileSystemUtils.readFile(agentsPath);\r\n } else {\r\n // Root AGENTS.md missing but project initialized? Create it.\r\n await FileSystemUtils.writeFile(\r\n agentsPath,\r\n TemplateManager.getAgentsTemplate()\r\n );\r\n return;\r\n }\r\n\r\n // Get the latest Skills section template\r\n const latestSkillsSection = await this.getSkillsSection();\r\n \r\n // Guarantee Universal Safety Rules are up to date\r\n const safetyMarker = '## Universal Safety Rules';\r\n const fullTemplate = TemplateManager.getAgentsTemplate();\r\n const safetyEndIndex = fullTemplate.indexOf('## Core Workflow');\r\n const safetySection = fullTemplate.substring(fullTemplate.indexOf(safetyMarker), safetyEndIndex).trim();\r\n\r\n if (existingContent.includes(safetyMarker)) {\r\n existingContent = this.replaceSafetyRules(existingContent, safetySection);\r\n } else {\r\n // Insert at the beginning or after header\r\n if (existingContent.startsWith('# ')) {\r\n const firstLineEnd = existingContent.indexOf('\\n') + 1;\r\n existingContent = existingContent.substring(0, firstLineEnd) + '\\n' + safetySection + '\\n\\n' + existingContent.substring(firstLineEnd);\r\n } else {\r\n existingContent = safetySection + '\\n\\n' + existingContent;\r\n }\r\n }\r\n\r\n // Update Core Workflow section (includes backup ignore rule, memory workflow, etc.)\r\n const coreWorkflowMarker = '## Core Workflow';\r\n const coreWorkflowEndMarker = '## Skills System';\r\n const coreWorkflowEndIndex = fullTemplate.indexOf(coreWorkflowEndMarker);\r\n const coreWorkflowStartIndex = fullTemplate.indexOf(coreWorkflowMarker);\r\n\r\n if (coreWorkflowStartIndex !== -1 && coreWorkflowEndIndex !== -1) {\r\n const coreWorkflowSection = fullTemplate.substring(coreWorkflowStartIndex, coreWorkflowEndIndex).trim();\r\n \r\n if (existingContent.includes(coreWorkflowMarker)) {\r\n existingContent = this.replaceSection(existingContent, coreWorkflowMarker, coreWorkflowSection);\r\n } else {\r\n // Append after Safety Rules\r\n const safetyEndPos = existingContent.indexOf('\\n## ', existingContent.indexOf(safetyMarker) + safetyMarker.length);\r\n if (safetyEndPos !== -1) {\r\n const before = existingContent.substring(0, safetyEndPos).trimEnd();\r\n const after = existingContent.substring(safetyEndPos);\r\n existingContent = before + '\\n\\n' + coreWorkflowSection + '\\n\\n' + after;\r\n }\r\n }\r\n }\r\n\r\n // Update Skills section\r\n let updatedContent = existingContent;\r\n if (existingContent.includes(skillsSectionMarker) || existingContent.includes('## Skills system')) {\r\n updatedContent = this.replaceSkillsSection(existingContent, latestSkillsSection);\r\n } else {\r\n updatedContent = this.appendSkillsSection(existingContent, latestSkillsSection);\r\n }\r\n\r\n // Update Memory section\r\n const oldMemoryMarker = '## Memory-Aware Development';\r\n const newMemoryMarker = '## Proactive Memory-Aware Development';\r\n \r\n // Extract new memory section from fullTemplate\r\n const memoryStartIndex = fullTemplate.indexOf(newMemoryMarker);\r\n if (memoryStartIndex !== -1) {\r\n let memoryEndIndex = fullTemplate.indexOf('\\n## ', memoryStartIndex + newMemoryMarker.length);\r\n if (memoryEndIndex === -1) memoryEndIndex = fullTemplate.length;\r\n \r\n const memorySection = fullTemplate.substring(memoryStartIndex, memoryEndIndex).trim();\r\n\r\n if (updatedContent.includes(oldMemoryMarker)) {\r\n updatedContent = this.replaceSection(updatedContent, oldMemoryMarker, memorySection);\r\n } else if (updatedContent.includes(newMemoryMarker)) {\r\n updatedContent = this.replaceSection(updatedContent, newMemoryMarker, memorySection);\r\n } else {\r\n // Append at the end\r\n updatedContent = updatedContent.trimEnd() + '\\n\\n' + memorySection;\r\n }\r\n }\r\n \r\n if (updatedContent !== existingContent) {\r\n await FileSystemUtils.writeFile(agentsPath, updatedContent);\r\n }\r\n }\r\n\r\n /**\r\n * Generic section replacer: replace content from marker to next ## header\r\n */\r\n private replaceSection(content: string, sectionMarker: string, newSection: string): string {\r\n const startIndex = content.indexOf(sectionMarker);\r\n if (startIndex === -1) return content;\r\n\r\n let endIndex = content.indexOf('\\n## ', startIndex + sectionMarker.length);\r\n if (endIndex === -1) {\r\n endIndex = content.length;\r\n }\r\n\r\n const before = content.substring(0, startIndex).trimEnd();\r\n const after = content.substring(endIndex);\r\n return before + '\\n\\n' + newSection + (after.trimStart().startsWith('\\n') ? '' : '\\n\\n') + after;\r\n }\r\n\r\n private replaceSkillsSection(existingContent: string, newSkillsSection: string): string {\r\n const startMarkers = ['## Skills System', '## Skills system', '### Skills System', '### Skills system'];\r\n \r\n let startIndex = -1;\r\n let foundMarker = '';\r\n \r\n for (const marker of startMarkers) {\r\n startIndex = existingContent.indexOf(marker);\r\n if (startIndex !== -1) {\r\n foundMarker = marker;\r\n break;\r\n }\r\n }\r\n\r\n if (startIndex === -1) {\r\n return this.appendSkillsSection(existingContent, newSkillsSection);\r\n }\r\n\r\n // Find the end of Skills section (before next ## section or end of file)\r\n let endIndex = existingContent.indexOf('\\n## ', startIndex + foundMarker.length);\r\n if (endIndex === -1) {\r\n endIndex = existingContent.indexOf('\\n### ', startIndex + foundMarker.length);\r\n }\r\n \r\n if (endIndex === -1) {\r\n endIndex = existingContent.length;\r\n }\r\n\r\n // Replace the section\r\n const before = existingContent.substring(0, startIndex).trimEnd();\r\n const after = existingContent.substring(endIndex);\r\n return before + '\\n\\n' + newSkillsSection + (after.trimStart().startsWith('\\n') ? '' : '\\n\\n') + after;\r\n }\r\n\r\n private replaceSafetyRules(existingContent: string, newSafetySection: string): string {\r\n const marker = '## Universal Safety Rules';\r\n const startIndex = existingContent.indexOf(marker);\r\n \r\n if (startIndex === -1) return existingContent;\r\n\r\n // Find end of section (next ## header)\r\n let endIndex = existingContent.indexOf('\\n## ', startIndex + marker.length);\r\n if (endIndex === -1) {\r\n endIndex = existingContent.length;\r\n }\r\n\r\n const before = existingContent.substring(0, startIndex).trimEnd();\r\n const after = existingContent.substring(endIndex);\r\n \r\n return before + '\\n\\n' + newSafetySection + (after.trimStart().startsWith('\\n') ? '' : '\\n\\n') + after;\r\n }\r\n\r\n private appendSkillsSection(existingContent: string, skillsSection: string): string {\r\n // Try to insert before \"## Rules\" section\r\n const rulesMarker = '\\n## Rules\\n';\r\n const rulesIndex = existingContent.indexOf(rulesMarker);\r\n \r\n if (rulesIndex !== -1) {\r\n const before = existingContent.substring(0, rulesIndex).trimEnd();\r\n const after = existingContent.substring(rulesIndex);\r\n return before + '\\n\\n' + skillsSection + '\\n\\n' + after;\r\n }\r\n\r\n // If no Rules section, try before any \"## Rules\" (without newline)\r\n const rulesMarker2 = '## Rules';\r\n const rulesIndex2 = existingContent.indexOf(rulesMarker2);\r\n if (rulesIndex2 !== -1 && rulesIndex2 > 0) {\r\n const before = existingContent.substring(0, rulesIndex2).trimEnd();\r\n const after = existingContent.substring(rulesIndex2);\r\n return before + '\\n\\n' + skillsSection + '\\n\\n' + after;\r\n }\r\n\r\n // If no Rules section, append at the end\r\n return existingContent.trimEnd() + '\\n\\n' + skillsSection;\r\n }\r\n\r\n\r\n private async getSkillsSection(): Promise<string> {\r\n return TemplateManager.getSkillsSection();\r\n }\r\n\r\n /**\r\n * Resolve core templates directory (same logic as skill.ts)\r\n */\r\n private async getCoreTemplatesDir(): Promise<string | null> {\r\n const possiblePaths: string[] = [];\r\n\r\n try {\r\n const packageJsonPath = require.resolve('../package.json');\r\n const packageDir = path.dirname(packageJsonPath);\r\n possiblePaths.push(\r\n join(packageDir, 'src', 'core', 'templates', 'skills'),\r\n join(packageDir, 'dist', 'core', 'templates', 'skills'),\r\n );\r\n } catch { /* continue */ }\r\n\r\n try {\r\n const packageJsonPath = require.resolve('heraspec/package.json');\r\n const packageDir = path.dirname(packageJsonPath);\r\n possiblePaths.push(\r\n join(packageDir, 'dist', 'core', 'templates', 'skills'),\r\n join(packageDir, 'src', 'core', 'templates', 'skills'),\r\n );\r\n } catch { /* continue */ }\r\n\r\n possiblePaths.push(\r\n join(__dirname, '..', '..', 'src', 'core', 'templates', 'skills'),\r\n join(__dirname, '..', 'core', 'templates', 'skills'),\r\n join(process.cwd(), 'src', 'core', 'templates', 'skills'),\r\n );\r\n\r\n for (const p of possiblePaths) {\r\n if (await FileSystemUtils.fileExists(p)) return p;\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Update installed built-in skills on re-init.\r\n *\r\n * Rules:\r\n * - Only update skills that exist in SKILL_TEMPLATE_MAP (built-in / known skills)\r\n * - Skip skills NOT in the template map (custom skills added by the project)\r\n * - For each matching skill: update skill.md + re-copy resourceDirs from template\r\n * but PRESERVE templates/, scripts/, examples/ sub-folders added by user\r\n */\r\n private async updateInstalledSkills(heraspecPath: string): Promise<void> {\r\n const skillsDir = path.join(heraspecPath, SKILLS_DIR_NAME);\r\n if (!(await FileSystemUtils.fileExists(skillsDir))) return;\r\n\r\n const coreTemplatesDir = await this.getCoreTemplatesDir();\r\n if (!coreTemplatesDir) return;\r\n\r\n const allTemplates = getAllSkillTemplates();\r\n let updatedCount = 0;\r\n let skippedCount = 0;\r\n\r\n // Build a set of known skill keys (skillName only, or \"projectType/skillName\")\r\n // for fast lookup when walking the installed skills directory\r\n const installedSkillPaths = await this.collectInstalledSkillPaths(skillsDir);\r\n\r\n for (const { skillPath, skillName, projectType } of installedSkillPaths) {\r\n // Check if this skill is a known built-in skill\r\n const templateInfo = getSkillTemplateInfo(skillName, projectType);\r\n\r\n if (!templateInfo) {\r\n // Not a built-in skill \u2014 custom project skill, leave it alone\r\n skippedCount++;\r\n continue;\r\n }\r\n\r\n const templateFile = path.join(coreTemplatesDir, templateInfo.templateFileName);\r\n if (!(await FileSystemUtils.fileExists(templateFile))) {\r\n skippedCount++;\r\n continue;\r\n }\r\n\r\n // Update skill.md with latest from template\r\n await FileSystemUtils.copyFile(templateFile, path.join(skillPath, 'skill.md'));\r\n\r\n // Update Vietnamese translation if it exists in template\r\n if (templateInfo.viFileName) {\r\n const viFile = path.join(coreTemplatesDir, templateInfo.viFileName);\r\n if (await FileSystemUtils.fileExists(viFile)) {\r\n await FileSystemUtils.copyFile(viFile, path.join(skillPath, 'skill.vi.md'));\r\n }\r\n }\r\n\r\n // Re-copy resourceDirs from template (overwrite built-in resources)\r\n // These are owned by the skill template, not by the user\r\n if (templateInfo.resourceDirs) {\r\n for (const resourceDir of templateInfo.resourceDirs) {\r\n const srcResourceDir = path.join(coreTemplatesDir, resourceDir);\r\n const destResourceDir = path.join(skillPath, resourceDir);\r\n\r\n if (await FileSystemUtils.fileExists(srcResourceDir)) {\r\n // Remove old and replace \u2014 these are template-owned directories\r\n if (await FileSystemUtils.fileExists(destResourceDir)) {\r\n await FileSystemUtils.removeDirectory(destResourceDir, true);\r\n }\r\n await FileSystemUtils.copyDirectory(srcResourceDir, destResourceDir);\r\n }\r\n }\r\n }\r\n\r\n // Ensure standard dirs exist (never removed, just ensured)\r\n for (const dir of ['templates', 'scripts', 'examples']) {\r\n await FileSystemUtils.createDirectory(path.join(skillPath, dir));\r\n }\r\n\r\n updatedCount++;\r\n }\r\n\r\n if (updatedCount > 0) {\r\n console.log(chalk.gray(` \u2713 Updated ${updatedCount} built-in skill(s)${skippedCount > 0 ? `, skipped ${skippedCount} custom skill(s)` : ''}`));\r\n }\r\n }\r\n\r\n /**\r\n * Walk heraspec/skills/ and return all installed skill paths with metadata\r\n */\r\n private async collectInstalledSkillPaths(\r\n skillsDir: string\r\n ): Promise<Array<{ skillPath: string; skillName: string; projectType?: string }>> {\r\n const result: Array<{ skillPath: string; skillName: string; projectType?: string }> = [];\r\n const entries = await FileSystemUtils.readDirectory(skillsDir);\r\n\r\n // Known project-type folder names (they contain sub-skill folders)\r\n const knownProjectTypes = [\r\n 'wordpress', 'wordpress-plugin', 'wordpress-theme',\r\n 'perfex-module', 'laravel-package', 'node-service',\r\n 'generic-webapp', 'backend-api', 'frontend-app', 'multi-stack',\r\n ];\r\n\r\n for (const entry of entries) {\r\n const entryPath = path.join(skillsDir, entry);\r\n const stats = await FileSystemUtils.stat(entryPath);\r\n if (!stats.isDirectory()) continue;\r\n\r\n if (knownProjectTypes.includes(entry)) {\r\n // It's a project-type folder \u2014 walk its children\r\n const subEntries = await FileSystemUtils.readDirectory(entryPath);\r\n for (const sub of subEntries) {\r\n const subPath = path.join(entryPath, sub);\r\n const subStats = await FileSystemUtils.stat(subPath);\r\n if (subStats.isDirectory() && await FileSystemUtils.fileExists(path.join(subPath, 'skill.md'))) {\r\n result.push({ skillPath: subPath, skillName: sub, projectType: entry });\r\n }\r\n }\r\n } else {\r\n // Cross-cutting skill\r\n if (await FileSystemUtils.fileExists(path.join(entryPath, 'skill.md'))) {\r\n result.push({ skillPath: entryPath, skillName: entry });\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Prompt user to bootstrap memory if historical specs are found\r\n */\r\n private async checkAndBootstrapMemory(heraspecPath: string, projectPath: string, spinner: ora.Ora): Promise<void> {\r\n const memorySkillDir = path.join(heraspecPath, SKILLS_DIR_NAME, 'project-memory');\r\n if (!(await FileSystemUtils.fileExists(memorySkillDir))) {\r\n // Automatically install project-memory skill\r\n spinner.stop();\r\n try {\r\n const { SkillCommand } = await import('../commands/skill.js');\r\n const skillCommand = new SkillCommand();\r\n console.log(chalk.cyan('\\n\uD83D\uDCE6 Auto-installing recommended skill: \"project-memory\"'));\r\n await skillCommand.add('project-memory', undefined, projectPath);\r\n console.log(); // Spacing\r\n } catch (err) {\r\n spinner.start();\r\n return; // failed to install, silently skip memory bootstrap\r\n }\r\n spinner.start();\r\n }\r\n\r\n // Checking if there are markdown files in specs or archives\r\n const specsDir = path.join(heraspecPath, SPECS_DIR_NAME);\r\n const archivesDir = path.join(heraspecPath, ARCHIVES_DIR_NAME);\r\n let hasHistoricalData = false;\r\n\r\n for (const dir of [specsDir, archivesDir]) {\r\n if (await FileSystemUtils.fileExists(dir)) {\r\n const entries = await FileSystemUtils.readDirectory(dir);\r\n if (entries.some(e => e.endsWith('.md'))) {\r\n hasHistoricalData = true;\r\n break;\r\n }\r\n // Sub-directories (e.g., changes/archives are folders with md in them)\r\n if (!hasHistoricalData) {\r\n for (const e of entries) {\r\n const fullPath = path.join(dir, e);\r\n const st = await FileSystemUtils.stat(fullPath);\r\n if (st.isDirectory()) {\r\n const subEntries = await FileSystemUtils.readDirectory(fullPath);\r\n if (subEntries.some(sub => sub.endsWith('.md'))) {\r\n hasHistoricalData = true;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (!hasHistoricalData) return;\r\n\r\n // Check if memory store already has significant data (>0 ops) to avoid bugging them every time\r\n const memoryDbPath = path.join(heraspecPath, 'memory', 'heraspec-memory.db');\r\n if (await FileSystemUtils.fileExists(memoryDbPath)) {\r\n // We'll skip forcing a prompt if the DB exists. The user can run heraspec memory bootstrap manually.\r\n // Or we could check the size, but skipping is safer to avoid annoyance.\r\n return;\r\n }\r\n\r\n // Stop the spinner before launching an interactive prompt to avoid stdout conflicts\r\n spinner.stop();\r\n \r\n console.log(chalk.cyan('\\n\uD83D\uDCA1 Tip: Your project has historical specs.'));\r\n const { confirm } = await import('@inquirer/prompts');\r\n const answer = await confirm({\r\n message: 'Would you like to bootstrap the \"project-memory\" system from these existing specs?',\r\n default: true,\r\n });\r\n\r\n if (answer) {\r\n try {\r\n const memoryCommand = new MemoryCommand();\r\n await memoryCommand.bootstrap({ yes: true }, projectPath);\r\n } catch (error) {\r\n console.log(chalk.red(`Bootstrap failed: ${error instanceof Error ? error.message : 'Unknown'}`));\r\n }\r\n }\r\n \r\n // Restart spinner for the rest of the flow\r\n spinner.start();\r\n }\r\n\r\n\r\n /**\r\n * Get the knowledge source directory from CLI package\r\n */\r\n private async getKnowledgeSourceDir(): Promise<string | null> {\r\n const possiblePaths: string[] = [];\r\n\r\n // Strategy 1: Resolve from package.json location\r\n try {\r\n const packageJsonPath = require.resolve('../package.json');\r\n const packageDir = path.dirname(packageJsonPath);\r\n\r\n possiblePaths.push(\r\n join(packageDir, 'src', 'core', 'templates', 'skills', 'knowledge'),\r\n join(packageDir, 'dist', 'core', 'templates', 'skills', 'knowledge'),\r\n );\r\n } catch {\r\n // Could not resolve, continue\r\n }\r\n\r\n // Strategy 2: npm installed package\r\n try {\r\n const packageJsonPath = require.resolve('heraspec/package.json');\r\n const packageDir = path.dirname(packageJsonPath);\r\n\r\n possiblePaths.push(\r\n join(packageDir, 'dist', 'core', 'templates', 'skills', 'knowledge'),\r\n join(packageDir, 'src', 'core', 'templates', 'skills', 'knowledge'),\r\n );\r\n } catch {\r\n // Package not found, continue\r\n }\r\n\r\n // Strategy 3: Relative paths from current file\r\n possiblePaths.push(\r\n join(__dirname, '..', '..', 'src', 'core', 'templates', 'skills', 'knowledge'),\r\n join(__dirname, '..', 'core', 'templates', 'skills', 'knowledge'),\r\n join(process.cwd(), 'src', 'core', 'templates', 'skills', 'knowledge'),\r\n );\r\n\r\n for (const possiblePath of possiblePaths) {\r\n if (await FileSystemUtils.fileExists(possiblePath)) {\r\n return possiblePath;\r\n }\r\n }\r\n\r\n return null;\r\n }\r\n\r\n /**\r\n * Deploy/update built-in knowledge base, preserving custom/ directory\r\n */\r\n private async deployKnowledge(heraspecPath: string): Promise<void> {\r\n const knowledgeDir = path.join(heraspecPath, KNOWLEDGE_DIR_NAME);\r\n const sourceDir = await this.getKnowledgeSourceDir();\r\n\r\n if (!sourceDir) {\r\n // No knowledge source available \u2014 skip silently\r\n return;\r\n }\r\n\r\n // Copy built-in files: index.json, README.md\r\n const builtinFiles = ['index.json', 'README.md'];\r\n for (const file of builtinFiles) {\r\n const srcFile = path.join(sourceDir, file);\r\n if (await FileSystemUtils.fileExists(srcFile)) {\r\n await FileSystemUtils.copyFile(srcFile, path.join(knowledgeDir, file));\r\n }\r\n }\r\n\r\n // Copy built-in category directories (frameworks, apis, platforms)\r\n // SKIP 'custom' \u2014 never touch user's custom knowledge\r\n const builtinCategories = ['frameworks', 'apis', 'platforms'];\r\n for (const category of builtinCategories) {\r\n const srcCategory = path.join(sourceDir, category);\r\n if (await FileSystemUtils.fileExists(srcCategory)) {\r\n const destCategory = path.join(knowledgeDir, category);\r\n // Remove old built-in category and replace with latest\r\n if (await FileSystemUtils.fileExists(destCategory)) {\r\n await FileSystemUtils.removeDirectory(destCategory, true);\r\n }\r\n await FileSystemUtils.copyDirectory(srcCategory, destCategory);\r\n }\r\n }\r\n\r\n // Create custom/ scaffold if it doesn't exist\r\n const customDir = path.join(knowledgeDir, 'custom');\r\n if (!(await FileSystemUtils.fileExists(customDir))) {\r\n await FileSystemUtils.createDirectory(customDir);\r\n await FileSystemUtils.writeFile(\r\n path.join(customDir, 'index.json'),\r\n JSON.stringify({\r\n version: '1.0',\r\n description: 'Custom knowledge entries \u2014 managed by user, never overwritten by CLI',\r\n entries: [],\r\n }, null, 2)\r\n );\r\n }\r\n }\r\n\r\n private async getSkillsReadmeTemplate(): Promise<string> {\r\n return `# Skills Directory\r\n\r\nThis directory contains reusable skills for HeraSpec projects.\r\n\r\n## What Are Skills?\r\n\r\nSkills are reusable patterns and workflows that help AI agents implement tasks consistently. Each skill contains:\r\n\r\n- **skill.md**: Complete guide on how to use the skill\r\n- **templates/**: Reusable templates\r\n- **scripts/**: Automation scripts\r\n- **examples/**: Good and bad examples\r\n\r\n## How Agents Use Skills\r\n\r\nWhen a task has a skill tag:\r\n\\`\\`\\`markdown\r\n## 1. Feature (projectType: perfex-module, skill: module-codebase)\r\n- [ ] Task 1.1\r\n\\`\\`\\`\r\n\r\nThe agent will:\r\n1. Find skill folder: \\`heraspec/skills/perfex-module/module-codebase/\\`\r\n2. Read \\`skill.md\\` to understand process\r\n3. Use templates and scripts from skill folder\r\n4. Follow guidelines in skill.md\r\n\r\n## Available Skills\r\n\r\nRun \\`heraspec skill list\\` to see all available skills.\r\n\r\n## UI/UX Skill - Creating Full Theme Packages\r\n\r\nThe **UI/UX skill** is particularly useful for creating complete website themes with multiple pages.\r\n\r\n### Quick Start\r\n\r\nWhen you need to create a full website package, use prompts like:\r\n\r\n\\`\\`\\`\r\nT\u1EA1o g\u00F3i website \u0111\u1EA7y \u0111\u1EE7 cho [PRODUCT_TYPE] v\u1EDBi style [STYLE_KEYWORDS].\r\nS\u1EED d\u1EE5ng skill ui-ux v\u1EDBi hybrid mode \u0111\u1EC3 search design intelligence.\r\nT\u1EA1o c\u00E1c trang: home, about, [other pages].\r\nStack: [html-tailwind/react/nextjs].\r\n\u0110\u1EA3m b\u1EA3o responsive, accessible, consistent design system.\r\n\\`\\`\\`\r\n\r\n### Prompt Templates\r\n\r\nFor detailed prompt examples and templates, see:\r\n- **Example Prompts**: \\`heraspec/skills/ui-ux/templates/example-prompt-full-theme.md\\`\r\n- **Prompt Templates**: \\`heraspec/skills/ui-ux/templates/prompt-template-full-theme.md\\`\r\n\r\nThese templates include:\r\n- Ready-to-use prompts for different website types (E-commerce, SaaS, Service, Blog, Portfolio)\r\n- Step-by-step instructions\r\n- Search command examples\r\n- Best practices\r\n\r\n### Search Modes\r\n\r\nUI/UX skill supports 3 search modes:\r\n- **BM25 (default)**: Fast keyword-based search, zero dependencies\r\n- **Vector**: Semantic search, ~15-20% better results (requires: \\`pip install sentence-transformers scikit-learn\\`)\r\n- **Hybrid**: Best of both, ~25% better results (requires: \\`pip install sentence-transformers scikit-learn\\`)\r\n\r\n**Usage:**\r\n\\`\\`\\`bash\r\n# BM25 (default)\r\npython3 heraspec/skills/ui-ux/scripts/search.py \"minimalism\" --domain style\r\n\r\n# Vector (semantic)\r\npython3 heraspec/skills/ui-ux/scripts/search.py \"elegant dark theme\" --domain style --mode vector\r\n\r\n# Hybrid (best)\r\npython3 heraspec/skills/ui-ux/scripts/search.py \"modern minimal design\" --domain style --mode hybrid\r\n\\`\\`\\`\r\n\r\n### Multi-Page Support\r\n\r\nDefault page set includes:\r\n1. Home\r\n2. About\r\n3. Post Details\r\n4. Category\r\n5. Pricing\r\n6. FAQ\r\n7. Contact\r\n8. Product Category (e-commerce)\r\n9. Product Details (e-commerce)\r\n\r\nSearch page types:\r\n\\`\\`\\`bash\r\npython3 heraspec/skills/ui-ux/scripts/search.py \"home homepage\" --domain pages\r\npython3 heraspec/skills/ui-ux/scripts/search.py \"pricing plans\" --domain pages\r\n\\`\\`\\`\r\n\r\n### Adding UI/UX Skill to Your Project\r\n\r\n1. Copy skill from HeraSpec core:\r\n \\`\\`\\`bash\r\n # Copy UI/UX skill\r\n cp -r /path/to/HeraSpec/src/core/templates/skills/ui-ux-skill.md heraspec/skills/ui-ux/\r\n cp -r /path/to/HeraSpec/src/core/templates/skills/scripts heraspec/skills/ui-ux/\r\n cp -r /path/to/HeraSpec/src/core/templates/skills/data heraspec/skills/ui-ux/\r\n cp -r /path/to/HeraSpec/src/core/templates/skills/templates heraspec/skills/ui-ux/\r\n \\`\\`\\`\r\n\r\n2. Or use \\`heraspec skill add ui-ux\\` (if available)\r\n\r\n3. Read \\`heraspec/skills/ui-ux/ui-ux-skill.md\\` for complete documentation\r\n\r\n### Flatsome UX Element Skill\r\n\r\nUse the **ux-element** skill when developing elements for UX Builder in Flatsome themes.\r\n\r\n**Usage:**\r\n\\`\\`\\`bash\r\nheraspec skill add ux-element --project-type wordpress\r\n\\`\\`\\`\r\n\r\nRead \\`heraspec/skills/wordpress/ux-element/skill.md\\` for the **Wrapping Rule** and template usage.\r\n\r\n## Creating New Skills\r\n\r\n1. Create skill folder structure\r\n2. Write \\`skill.md\\` following the template\r\n3. Add templates, scripts, examples as needed\r\n\r\nSee \\`docs/SKILLS_STRUCTURE_PROPOSAL.md\\` for detailed structure.\r\n`;\r\n }\r\n\r\n private async getUIUXQuickReference(): Promise<string> {\r\n return `# UI/UX Skill - Quick Reference Guide\r\n\r\nQuick guide for creating prompts to build full theme packages with multiple pages using the ui-ux skill.\r\n\r\n## \uD83D\uDCCB Basic Prompt Template\r\n\r\n\\`\\`\\`\r\nCreate a complete website package for [PRODUCT_TYPE] with the following requirements:\r\n\r\n**Project Information:**\r\n- Product type: [SaaS / E-commerce / Service / Portfolio / etc.]\r\n- Style: [minimal / elegant / modern / bold / etc.]\r\n- Industry: [Healthcare / Fintech / Beauty / etc.]\r\n- Stack: [html-tailwind / react / nextjs / etc.]\r\n- Pages to create: home, about, [add other pages if needed]\r\n\r\n**Process:**\r\n1. Use skill ui-ux to search design intelligence with hybrid mode\r\n2. Create shared components first (Header, Footer, Button, Card)\r\n3. Implement pages in order\r\n4. Ensure consistency in colors, typography, spacing\r\n5. Verify with pre-delivery checklist\r\n\r\n**Quality Requirements:**\r\n- \u2705 Consistent design system\r\n- \u2705 Responsive (320px, 768px, 1024px, 1440px)\r\n- \u2705 Accessible (WCAG AA minimum)\r\n- \u2705 Performance optimized\r\n\\`\\`\\`\r\n\r\n## \uD83C\uDFAF Specific Prompt Examples\r\n\r\n### E-Commerce\r\n\\`\\`\\`\r\nCreate a complete website package for an online fashion store.\r\n\r\nProduct type: E-commerce Luxury\r\nStyle: elegant, premium, sophisticated\r\nStack: Next.js with Tailwind CSS\r\nPages: home, about, product category, product details, cart, checkout, thank you, faq, contact\r\n\r\nUse skill ui-ux with hybrid mode. Focus on conversion optimization.\r\n\\`\\`\\`\r\n\r\n### SaaS\r\n\\`\\`\\`\r\nCreate a complete website package for a project management SaaS platform.\r\n\r\nProduct type: SaaS (General)\r\nStyle: modern, clean, professional\r\nStack: React with Tailwind CSS\r\nPages: home, about, pricing, features, faq, contact, login, register, dashboard\r\n\r\nUse skill ui-ux with hybrid mode. Ensure professional and trustworthy.\r\n\\`\\`\\`\r\n\r\n### Service Business\r\n\\`\\`\\`\r\nCreate a complete website package for a healthcare service.\r\n\r\nProduct type: Beauty & Wellness Service\r\nStyle: elegant, minimal, soft, professional\r\nStack: html-tailwind\r\nPages: home, about, services, blog listing, post details, category, pricing, faq, contact\r\n\r\nUse skill ui-ux with hybrid mode. Focus on trust and credibility.\r\n\\`\\`\\`\r\n\r\n## \uD83D\uDD0D Search Modes\r\n\r\n### BM25 (Default)\r\n\\`\\`\\`bash\r\npython3 heraspec/skills/ui-ux/scripts/search.py \"minimalism\" --domain style\r\n\\`\\`\\`\r\n- \u2705 Fast, zero dependencies\r\n- \u2705 Best for exact keyword matches\r\n\r\n### Vector (Semantic)\r\n\\`\\`\\`bash\r\npython3 heraspec/skills/ui-ux/scripts/search.py \"elegant dark theme\" --domain style --mode vector\r\n\\`\\`\\`\r\n- \u2705 Understands meaning and synonyms\r\n- \u2705 ~15-20% better results\r\n- \u26A0\uFE0F Requires: \\`pip install sentence-transformers scikit-learn\\`\r\n\r\n### Hybrid (Best)\r\n\\`\\`\\`bash\r\npython3 heraspec/skills/ui-ux/scripts/search.py \"modern minimal design\" --domain style --mode hybrid\r\n\\`\\`\\`\r\n- \u2705 Combines BM25 + Vector\r\n- \u2705 ~25% better results\r\n- \u26A0\uFE0F Requires: \\`pip install sentence-transformers scikit-learn\\`\r\n\r\n## \uD83D\uDCC4 Default Page Set\r\n\r\nWhen creating a \"complete website package\", the default set includes 9 pages:\r\n\r\n1. **Home** - Main homepage\r\n2. **About** - Company/story page\r\n3. **Post Details** - Blog/article detail\r\n4. **Category** - Blog/category listing\r\n5. **Pricing** - Pricing plans\r\n6. **FAQ** - Frequently asked questions\r\n7. **Contact** - Contact form\r\n8. **Product Category** - E-commerce category (if applicable)\r\n9. **Product Details** - E-commerce product detail (if applicable)\r\n\r\n## \uD83D\uDD27 Search Page Types\r\n\r\n\\`\\`\\`bash\r\n# Home page\r\npython3 heraspec/skills/ui-ux/scripts/search.py \"home homepage\" --domain pages\r\n\r\n# About page\r\npython3 heraspec/skills/ui-ux/scripts/search.py \"about company story\" --domain pages\r\n\r\n# Pricing page\r\npython3 heraspec/skills/ui-ux/scripts/search.py \"pricing plans tiers\" --domain pages\r\n\r\n# E-commerce pages\r\npython3 heraspec/skills/ui-ux/scripts/search.py \"product-category shop catalog\" --domain pages\r\npython3 heraspec/skills/ui-ux/scripts/search.py \"product-detail single-product\" --domain pages\r\n\\`\\`\\`\r\n\r\n## \uD83D\uDCDA Detailed Documentation\r\n\r\nAfter copying UI/UX skill to your project, see:\r\n- \\`heraspec/skills/ui-ux/ui-ux-skill.md\\` - Complete skill documentation\r\n- \\`heraspec/skills/ui-ux/templates/example-prompt-full-theme.md\\` - Detailed prompt examples\r\n- \\`heraspec/skills/ui-ux/templates/prompt-template-full-theme.md\\` - Copy-paste templates\r\n\r\n## \uD83D\uDCA1 Tips\r\n\r\n1. **Always mention \"skill ui-ux\"** - Agent will know to use this skill\r\n2. **Encourage using hybrid mode** - Best results\r\n3. **List all pages clearly** - Agent knows exact scope\r\n4. **Require consistency** - Ensures unified design system\r\n5. **Mention pre-delivery checklist** - Agent will verify before delivering\r\n\r\n## \uD83D\uDE80 Quick Start\r\n\r\n1. Copy UI/UX skill to project:\r\n \\`\\`\\`bash\r\n cp -r /path/to/HeraSpec/src/core/templates/skills/ui-ux-skill.md heraspec/skills/ui-ux/\r\n cp -r /path/to/HeraSpec/src/core/templates/skills/scripts heraspec/skills/ui-ux/\r\n cp -r /path/to/HeraSpec/src/core/templates/skills/data heraspec/skills/ui-ux/\r\n cp -r /path/to/HeraSpec/src/core/templates/skills/templates heraspec/skills/ui-ux/\r\n \\`\\`\\`\r\n\r\n2. Use prompt template from above\r\n\r\n3. Agent will automatically:\r\n - Search design intelligence with skill ui-ux\r\n - Create shared components\r\n - Implement each page\r\n - Verify with checklist\r\n`;\r\n }\r\n\r\n /**\r\n * Update related markdown files in the project (README.md, etc.)\r\n */\r\n private async updateRelatedMarkdownFiles(projectPath: string): Promise<void> {\r\n // Update README.md if exists\r\n const readmePath = path.join(projectPath, 'README.md');\r\n if (await FileSystemUtils.fileExists(readmePath)) {\r\n await this.updateReadmeFile(readmePath);\r\n }\r\n }\r\n\r\n /**\r\n * Update README.md with HeraSpec information\r\n */\r\n private async updateReadmeFile(readmePath: string): Promise<void> {\r\n const existingContent = await FileSystemUtils.readFile(readmePath);\r\n const heraspecSection = this.getHeraSpecReadmeSection();\r\n\r\n // Check if HeraSpec section already exists\r\n const sectionMarkers = [\r\n '## HeraSpec',\r\n '## HeraSpec Development',\r\n '### HeraSpec',\r\n '### HeraSpec Development',\r\n '<!-- HeraSpec Section -->',\r\n ];\r\n\r\n let hasHeraSpecSection = false;\r\n let sectionStartIndex = -1;\r\n let sectionEndIndex = -1;\r\n\r\n for (const marker of sectionMarkers) {\r\n const index = existingContent.indexOf(marker);\r\n if (index !== -1) {\r\n hasHeraSpecSection = true;\r\n sectionStartIndex = index;\r\n // Find the end of the section (next ## or end of file)\r\n sectionEndIndex = existingContent.indexOf('\\n## ', index + marker.length);\r\n if (sectionEndIndex === -1) {\r\n sectionEndIndex = existingContent.indexOf('\\n### ', index + marker.length);\r\n }\r\n if (sectionEndIndex === -1) {\r\n sectionEndIndex = existingContent.length;\r\n }\r\n break;\r\n }\r\n }\r\n\r\n if (hasHeraSpecSection && sectionStartIndex !== -1) {\r\n // Update existing section\r\n const before = existingContent.substring(0, sectionStartIndex).trimEnd();\r\n const after = existingContent.substring(sectionEndIndex);\r\n const updatedContent = before + '\\n\\n' + heraspecSection + (after.trimStart().startsWith('\\n') ? '' : '\\n\\n') + after;\r\n await FileSystemUtils.writeFile(readmePath, updatedContent);\r\n } else {\r\n // Add new section\r\n // Try to insert before common sections like \"## Development\", \"## Setup\", \"## Contributing\"\r\n const insertBeforeMarkers = [\r\n '\\n## Development',\r\n '\\n## Setup',\r\n '\\n## Contributing',\r\n '\\n## Installation',\r\n '\\n## Getting Started',\r\n ];\r\n\r\n let inserted = false;\r\n for (const marker of insertBeforeMarkers) {\r\n const index = existingContent.indexOf(marker);\r\n if (index !== -1) {\r\n const before = existingContent.substring(0, index).trimEnd();\r\n const after = existingContent.substring(index);\r\n const updatedContent = before + '\\n\\n' + heraspecSection + '\\n\\n' + after;\r\n await FileSystemUtils.writeFile(readmePath, updatedContent);\r\n inserted = true;\r\n break;\r\n }\r\n }\r\n\r\n if (!inserted) {\r\n // Append at the end\r\n const updatedContent = existingContent.trimEnd() + '\\n\\n' + heraspecSection;\r\n await FileSystemUtils.writeFile(readmePath, updatedContent);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Get HeraSpec section content for README.md\r\n */\r\n private getHeraSpecReadmeSection(): string {\r\n return `<!-- HeraSpec Section -->\r\n## HeraSpec Development\r\n\r\nThis project uses [HeraSpec](https://github.com/your-org/heraspec) for spec-driven development.\r\n\r\n### Quick Start\r\n\r\n\\`\\`\\`bash\r\n# Initialize HeraSpec (if not already done)\r\nheraspec init\r\n\r\n# List active changes\r\nheraspec list\r\n\r\n# View a change\r\nheraspec show <change-name>\r\n\r\n# Validate changes\r\nheraspec validate <change-name>\r\n\\`\\`\\`\r\n\r\n### Project Structure\r\n\r\n- \\`heraspec/project.md\\` - Project overview and configuration\r\n- \\`heraspec/specs/\\` - Source of truth specifications\r\n- \\`heraspec/changes/\\` - Active changes in progress\r\n- \\`heraspec/skills/\\` - Reusable skills for AI agents\r\n- \\`AGENTS.heraspec.md\\` - AI agent instructions\r\n\r\n### Working with Changes\r\n\r\n1. **Create a change**: Ask AI to create a HeraSpec change, or create manually\r\n2. **Refine specs**: Review and update delta specs in \\`heraspec/specs/<change-name>/\\`\r\n3. **Implement**: Follow tasks in \\`heraspec/changes/<change-name>/tasks.md\\`\r\n4. **Archive**: Run \\`heraspec archive <change-name> --yes\\` when complete\r\n\r\n### Skills\r\n\r\nAdd skills to your project:\r\n\r\n\\`\\`\\`bash\r\n# List available skills\r\nheraspec skill list\r\n\r\n# Add a skill\r\nheraspec skill add ui-ux\r\nheraspec skill add unit-test\r\n\r\n# View skill details\r\nheraspec skill show ui-ux\r\n\\`\\`\\`\r\n\r\nFor more information, see the [HeraSpec documentation](https://github.com/your-org/heraspec/docs).\r\n\r\n---\r\n\r\n*This section is automatically updated by \\`heraspec init\\`. Last updated: ${new Date().toISOString().split('T')[0]}*`;\r\n }\r\n}\r\n\r\n", "/**\r\n * HeraSpec Templates\r\n */\r\n\r\nexport class TemplateManager {\r\n static getProjectTemplate(): string {\r\n return `# HeraSpec Project\r\n\r\n## \u26A1 Slash Commands (Agent Triggers)\r\n\r\nWhen the user types messages starting with a slash (/), you MUST intercept them as action triggers rather than conversational queries. Please execute the corresponding terminal commands immediately:\r\n\r\n- /heraspec [args] : Run the heraspec CLI tool with the provided arguments (e.g. /heraspec validate my-change)\r\n- /sync : Run heraspec sync <current-change>\r\n- /archive : Run heraspec archive <current-change> --yes\r\n- /skill [name] : Run heraspec skill add [name]\r\n- /hotfix [title] : Run heraspec hotfix [title]\r\n\r\n*If the user types a slash command, do not explain what you are going to do, just run the terminal command and report the output.*\r\n\r\n## Overview\r\nDescribe your project here.\r\n\r\n## Architecture\r\nDescribe the high-level architecture: entry points, module structure, data flow.\r\n\r\n## Key Dependencies\r\nList critical dependencies and their purposes (e.g., better-sqlite3 for memory, commander for CLI).\r\n\r\n## Conventions\r\nDefine coding standards, architectural patterns, and conventions to follow.\r\n`;\r\n }\r\n\r\n static getAgentsTemplate(): string {\r\n return `# HeraSpec \u2014 AI Agent Instructions\r\n\r\nThis document defines the workflow for AI agents working with HeraSpec.\r\n\r\n## Universal Safety Rules\r\n\r\n- **NO AUTO-COMMIT**: Agent MUST NOT perform \\`git commit\\` or \\`git push\\` autonomously. This task is reserved for the User unless explicitly ordered.\r\n- **NO AUTO-PUBLISH**: Agent MUST NOT perform \\`npm publish\\` or trigger automated releases/deployments autonomously.\r\n- **SKILL PREREQUISITE**: If a task maps to a skill (e.g., \"Generate documentation\"), you **MUST** verify the skill folder exists in \\`heraspec/skills/\\`. If missing:\r\n - **Preferred**: Proactively install it via \\`heraspec skill add <name>\\` (e.g., \\`heraspec skill add documents\\`) if you have terminal access.\r\n - **Fallback**: If you cannot install it, **STOP** and ask the user to add it. **DO NOT** attempt manual generation without the skill.\r\n- **USER CONFIRMATION**: For destructive actions or public releases, always request explicit User approval first.\r\n\r\n### Restricted Commands (REQUIRE USER CONFIRMATION)\r\n\r\nThe following commands are classified by risk level. You **MUST NOT** execute them without explicit user confirmation/approval in the chat, especially if they are outside the source workspace or involve deletion.\r\n\r\n#### GROUP 1 \u2013 EXTREMELY DANGEROUS (DATA DESTRUCTION, HARD / IMPOSSIBLE TO RECOVER)\r\n- \\`rm -rf\\` : Recursive delete + no prompt, can wipe entire system\r\n- \\`rm -r\\` : Delete directory and all contents\r\n- \\`rm\\` : Delete file directly, bypassing trash\r\n- \\`unlink\\` : Delete file at filesystem level, cannot undo\r\n- \\`shred\\` : Overwrite data multiple times to make it unrecoverable\r\n- \\`wipe\\` : Permanently wipe data on disk\r\n- \\`dd\\` : Write/copy raw blocks, easily destroy disk or partition\r\n- \\`mkfs\\`, \\`mkfs.ext4\\`, \\`mkfs.xfs\\` : Create new filesystem, wiping old data\r\n- \\`format\\`, \\`Format-Volume\\` : Format drive/volume\r\n\r\n#### GROUP 2 \u2013 HIGH DANGER (DELETE DIRECTORY / MULTIPLE FILES)\r\n- \\`rmdir\\` : Delete directory\r\n- \\`rd\\`, \\`rmdir /s\\` : Windows delete directory\r\n- \\`Remove-Item -Recurse\\`, \\`Remove-Item\\` : PowerShell delete\r\n- \\`del /s\\`, \\`erase /s\\` : CMD batch delete\r\n\r\n#### GROUP 3 \u2013 MEDIUM DANGER (DELETE FILE / OVERWRITE)\r\n- \\`del\\`, \\`erase\\` : Delete file\r\n- \\`Clear-Content\\` : Clear file content\r\n- \\`cp --remove-destination\\` : Overwrite destination by deleting first\r\n\r\n#### GROUP 4 \u2013 INDIRECT DANGER (DATA LOSS)\r\n- \\`mv\\` : Move / overwrite file, old data lost\r\n- \\`rsync --delete\\` : Delete file at destination if not in source\r\n- \\`install\\` : Overwrite system files\r\n\r\n#### GROUP 5 \u2013 DISK / PARTITION MANAGEMENT\r\n- \\`fdisk\\`, \\`cfdisk\\`, \\`parted\\`, \\`diskpart\\` : Partition management\r\n- \\`mount\\`, \\`umount\\` : Filesystem mounting\r\n\r\n#### GROUP 6 \u2013 LESS DANGEROUS (POTENTIAL CONSEQUENCES)\r\n- \\`truncate\\` : Cutt off file content\r\n- \\`chown\\`, \\`chmod\\` : Change ownership/permissions\r\n- \\`attrib\\` : Change attributes\r\n\r\n## Core Workflow\r\n\r\n### Step 1 \u2014 Create a Change\r\n\r\n**When creating changes, ALWAYS read heraspec/project.md first to understand:**\r\n- Project types being used\r\n- Tech stack and conventions\r\n- Existing architecture patterns\r\n- Coding standards\r\n\r\n> **IGNORE backup files**: Files like \\\\\\`project.back1.md\\\\\\`, \\\\\\`project.back2.md\\\\\\`, etc. are automatic backups created during \\\\\\`heraspec init\\\\\\` updates. NEVER read or reference them unless explicitly asked by the user. Only \\\\\\`project.md\\\\\\` is the source of truth.\r\n\r\n**Then scaffold:**\r\n- \\`heraspec/changes/<slug>/\\` - Create proposal.md, tasks.md, design.md (optional)\r\n- \\`heraspec/specs/<slug>/\\` - Create delta specs here (NOT inside changes folder)\r\n\r\n**If user asks to create changes based on project.md:**\r\n1. Read \\`heraspec/project.md\\` thoroughly\r\n2. Identify all features/capabilities mentioned\r\n3. Create separate changes for each major feature\r\n4. Ensure each change follows project.md conventions\r\n5. Use correct project types and skills from project.md\r\n\r\n### Step 2 \u2014 Refine Specs\r\n- Update delta specs in \\`heraspec/specs/<slug>/\\`\r\n- Never modify source-of-truth specs directly\r\n\r\n### Step 3 \u2014 Approval\r\n- Wait for user: \"Specs approved.\"\r\n\r\n### Step 4 \u2014 Implementation\r\n\r\n**CRITICAL: When implementing tasks, ALWAYS use Skills system:**\r\n\r\n1. **Read task line** to identify skill:\r\n \\`\\`\\`markdown\r\n ## 1. Perfex module \u2013 Category Management (projectType: perfex-module, skill: module-codebase)\r\n - [ ] 1.1 Create module structure\r\n \\`\\`\\`\r\n\r\n2. **Find skill folder**:\r\n - Project-specific: \\`heraspec/skills/<project-type>/<skill-name>/\\`\r\n - Cross-cutting: \\`heraspec/skills/<skill-name>/\\`\r\n\r\n3. **Read skill.md**:\r\n - Understand purpose, steps, inputs, outputs\r\n - Follow tone, rules, and limitations\r\n - Check available templates and scripts\r\n\r\n4. **Use skill resources**:\r\n - Run scripts from \\`scripts/\\` folder if needed\r\n - Use templates from \\`templates/\\` folder\r\n - Reference examples from \\`examples/\\` folder\r\n\r\n5. **Implement following skill.md guidance**:\r\n - Follow step-by-step process\r\n - Use correct naming conventions\r\n - Apply code style rules\r\n - Respect limitations\r\n\r\n**Example workflow:**\r\n- Task: \\`(projectType: perfex-module, skill: module-codebase)\\`\r\n- Agent reads: \\`heraspec/skills/perfex-module/module-codebase/skill.md\\`\r\n- Agent follows: Steps, uses templates, runs scripts\r\n- Agent implements: According to skill.md guidelines\r\n\r\n**Special case - UI/UX skill:**\r\n- Task: \\`(skill: ui-ux)\\`\r\n- Agent reads: \\`heraspec/skills/ui-ux/skill.md\\`\r\n- Agent MUST use search scripts before implementing:\r\n \\`\\`\\`bash\r\n # Search for design intelligence\r\n python3 heraspec/skills/ui-ux/scripts/search.py \"<keyword>\" --domain <domain>\r\n python3 heraspec/skills/ui-ux/scripts/search.py \"<keyword>\" --stack <stack>\r\n \\`\\`\\`\r\n- Agent synthesizes search results\r\n- Agent implements with proper colors, fonts, styles from search results\r\n- Agent verifies with pre-delivery checklist\r\n\r\n**Special case - Flatsome UX Element skill:**\r\n- Task: \\`(projectType: wordpress, skill: ux-element)\\`\r\n- Agent reads: \\`heraspec/skills/wordpress/ux-element/skill.md\\`\r\n- Agent MUST follow the **Wrapping Rule**: Use \\`<span>\\` with \\`id=\"{{:: shortcode.$id }}\"\\`\r\n- Agent uses templates from \\`heraspec/skills/wordpress/ux-element/templates/\\` (Controller, Shortcode, HTML Template, SVG Thumbnail)\r\n- Agent ensures real-time preview support in AngularJS template.\r\n- **Variable Translation**: Variables with underscores in PHP (e.g., \\`bg_color\\`) MUST be accessed via camelCase in AngularJS (e.g., \\`shortcode.options.bgColor\\`).\r\n\r\n**Special case - Plugin Check skill:**\r\n- Task: \\`(projectType: wordpress-plugin, skill: plugin-check)\\`\r\n- Install: \\`heraspec skill add plugin-check --project-type wordpress-plugin\\`\r\n- Agent reads: \\`heraspec/skills/wordpress-plugin/plugin-check/skill.md\\`\r\n- Agent runs WordPress Plugin Check (PCP) tool\r\n- Agent fixes coding standard issues iteratively until all pass\r\n\r\n**Special case - Plugin Directory skill:**\r\n- Task: \\`(projectType: wordpress-plugin, skill: plugin-directory)\\`\r\n- Install: \\`heraspec skill add plugin-directory --project-type wordpress-plugin\\`\r\n- Agent reads: \\`heraspec/skills/wordpress-plugin/plugin-directory/skill.md\\`\r\n- Agent MUST review plugin against **18 WordPress.org Directory Guidelines**:\r\n 1. GPL Compatibility\r\n 2. Developer Responsibility\r\n 3. Stable Version Availability\r\n 4. Human Readable Code\r\n 5. No Trialware\r\n 6. Software as a Service\r\n 7. User Tracking Consent\r\n 8. No External Executable Code\r\n 9. Legal and Ethical Conduct\r\n 10. External Links and Credits\r\n 11. Admin Dashboard Experience\r\n 12. No Spam in Public Pages\r\n 13. WordPress Default Libraries\r\n 14. Commit Frequency\r\n 15. Version Number Increment\r\n 16. Complete Plugin Required\r\n 17. Trademark and Copyright\r\n 18. Directory Maintenance Rights\r\n- Agent generates a **Compliance Report** with:\r\n - \u2705 Passed items\r\n - \u26A0\uFE0F Items needing review \r\n - \u274C Violations with file paths and line numbers\r\n- **CRITICAL**: Agent MUST present full report and **wait for user confirmation** before making changes\r\n- Reference guideline numbers (e.g., \"Guideline 7: User Tracking Consent\")\r\n\r\n\r\n- Follow tasks.md\r\n- Mark tasks completed: \\`- [x]\\`\r\n\r\n### Step 5 \u2014 Archive\r\n- Run: \\`heraspec archive <slug> --yes\\`\r\n- This merges delta specs into source specs\r\n- Moves change folder to archives\r\n\r\n#### Handling Parallel Merge Conflicts\r\nIf \\`heraspec archive\\` throws a **Parallel Merge Conflict** error:\r\n1. It means someone else modified the base requirement in the source spec while you were working.\r\n2. **DO NOT PANIC** and **DO NOT OVERWRITE** manually.\r\n3. Run: \\`heraspec sync <slug>\\`\r\n4. The system will automatically update your fingerprint to match the new source spec and warn you.\r\n5. Review your delta spec again. Make sure your \\`MODIFIED/REMOVED\\` requirements still make sense given the new source.\r\n6. Once verified, run \\`heraspec archive <slug> --yes\\` again.\r\n\r\n## Spec Format\r\n\r\nSpecs must include:\r\n- \\`## Meta\\` section with project type, domain, stack\r\n- \\`## Purpose\\`\r\n- \\`## Requirements\\` with scenarios\r\n\r\n## Delta Spec Format\r\n\r\nDelta specs use:\r\n- \\`## ADDED Requirements\\`\r\n- \\`## MODIFIED Requirements\\`\r\n- \\`## REMOVED Requirements\\`\r\n\r\n## Tasks Format\r\n\r\nTasks grouped by project type and skill:\r\n\\`\\`\\`\r\n## 1. WordPress plugin \u2013 admin settings page (projectType: wordpress-plugin, skill: admin-settings-page)\r\n- [ ] Task description\r\n\\`\\`\\`\r\n\r\n## Skills System\r\n\r\n**CRITICAL: Mandatory Prerequisite Check**\r\n\r\n1. **Stop & Verify**: If you are asked to implement a task requiring a skill (e.g., \"Generate documentation...\", \"Create UI/UX...\", etc.), you MUST first check if the skill folder exists in \\`heraspec/skills/\\`.\r\n2. **Missing Skill = AUTO-INSTALL OR STOP**: If the skill folder does NOT exist:\r\n - **Option A (Preferred)**: If you can run commands, execute \\`heraspec skill add <skill-name>\\` immediately.\r\n - **Option B (Fallback)**: If you cannot run commands, **STOP** and ask the user to run it.\r\n > \"Tip: Add the 'documents' skill for premium HTML & Landing Page support: \r\n > heraspec skill add documents\"\r\n - **DO NOT** create a task plan or attempt manual generation without the skill language.\r\n3. **Execute After Install**: Only after the skill folder is created (or installed), read the \\`skill.md\\` and proceed with the task.\r\n\r\n**Example prompt for Documents skill:**\r\nIf you need to generate multi-format documentation, use this prompt:\r\n> \"Generate documentation with skill documents for [project-name]. Include:\r\n> - Concise overview (documentations/documentation.txt)\r\n> - Technical Markdown (documentations/documentation.md)\r\n> - Interactive HTML (documentations/documentation.html)\r\n> - Premium Documentation Landing Page (documentations/documentation-landing-page.html)\r\n> - CRITICAL: Save all files in the /documentations directory (create it if missing).\"\r\n\r\n**Dynamic Documentation Generation**:\r\nWhen generating documentation, do NOT simply fill a template. The Agent MUST:\r\n1. **Create** the \\`/documentations\\` directory if it does not exist.\r\n2. **Design** a custom layout and content structure suitable for the project type.\r\n3. **Synchronize** with the \\`ui-ux\\` skill for premium visual design (colors, typography, animations).\r\n4. **Scan All Specs**: If project-wide, read \\`heraspec/project.md\\` and all files in \\`heraspec/specs/\\` to synthesize the content.\r\n\r\n### Skill Discovery & Usage\r\n\r\n- List all skills: Check \\`heraspec/skills/\\` directory\r\n- Project-specific skills: \\`heraspec/skills/<project-type>/\\`\r\n- Cross-cutting skills: \\`heraspec/skills/<skill-name>/\\` (root level)\r\n- **Consistency**: Follow the step-by-step process in the skill's \\`skill.md\\`.\r\n\r\n### When Change Has Multiple Skills\r\n\r\n**Important**: Each task group uses ONE skill. When working on a task group, agent MUST use that skill's skill.md.\r\n\r\nExample with multiple skills in one change:\r\n\\`\\`\\`\r\n## 1. WordPress module \u2013 Feature (skill: admin-settings-page)\r\n- [ ] Task 1.1 Create module structure\r\n- [ ] Task 1.2 Configure registration\r\n\r\n## 2. UI/UX \u2013 Admin Interface (skill: ui-ux)\r\n- [ ] Task 2.1 Design color palette\r\n- [ ] Task 2.2 Create component styles\r\n\r\n## 3. Documents \u2013 User Guide (skill: documents)\r\n- [ ] Task 3.1 Write technical docs\r\n\\`\\`\\`\r\n\r\n**Key rule**: Switch skill.md when switching task groups!\r\n\r\n## Proactive Memory-Aware Development\r\n\r\nIf \\\\\\`heraspec/skills/project-memory/\\\\\\` exists, the agent MUST proactively use memory to maintain project context. DO NOT wait for the user to prompt you to use memory.\r\n\r\n### CRITICAL RULES FOR AUTOMATIC MEMORY USAGE\r\n1. **Always Check Context First**: At the beginning of a complex task or when encountering an unfamiliar codebase area, you MUST autonomously run \\\\\\`heraspec memory context\\\\\\` or \\\\\\`heraspec memory search \"keywords\"\\\\\\` BEFORE writing any code.\r\n2. **Auto-Log via Archive**: You DO NOT need to run \\\\\\`heraspec memory log\\\\\\` manually. Every time you successfully implement a feature and run \\\\\\`heraspec archive <change-name>\\\\\\`, the system will automatically read your proposal and log the memory observation under the hood. Just use \\\\\\`heraspec archive\\\\\\` as normal!\r\n3. **Session Summary**: (Optional) When wrapping up a large session, you can run \\\\\\`heraspec memory summarize --request \"...\" --completed \"...\"\\\\\\` to compress knowledge, though \\\\\\`archive\\\\\\` already auto-logs completed features.\r\n\r\n### When to SKIP Memory\r\n- Simple bug fixes, typo corrections, formatting changes\r\n- Trivial tasks that take < 5 minutes\r\n- When doing what the agent's built-in context already covers\r\n\r\n### Smart Code Exploration\r\nIf \\\\\\`heraspec/skills/smart-explore/\\\\\\` exists, prefer token-efficient exploration:\r\n- \\\\\\`heraspec explore outline \\u003cfile\\u003e\\\\\\` \u2192 View structure (~1K tokens vs ~12K full file)\r\n- \\\\\\`heraspec explore search \"\\u003cquery\\u003e\" \\u003cpath\\u003e\\\\\\` \u2192 Find symbols across codebase\r\n- \\\\\\`heraspec explore unfold \\u003cfile\\u003e \\u003csymbol\\u003e\\\\\\` \u2192 Read just one function\r\n`;\r\n }\r\n\r\n static getSkillsSection(): string {\r\n return `## Skills System\r\n\r\n**CRITICAL: Mandatory Prerequisite Check**\r\n\r\n1. **Stop & Verify**: If you are asked to implement a task requiring a skill (e.g., \"Generate documentation...\", \"Create UI/UX...\", etc.), you MUST first check if the skill folder exists in \\`heraspec/skills/\\`.\r\n2. **Missing Skill = AUTO-INSTALL OR STOP**: If the skill folder does NOT exist:\r\n - **Option A (Preferred)**: If you can run commands, execute \\`heraspec skill add <skill-name>\\` immediately.\r\n - **Option B (Fallback)**: If you cannot run commands, **STOP** and ask the user to run it.\r\n > \"Tip: Add the 'documents' skill for premium HTML & Landing Page support: \r\n > heraspec skill add documents\"\r\n - **DO NOT** create a task plan or attempt manual generation without the skill language.\r\n3. **Execute After Install**: Only after the skill folder is created (or installed), read the \\`skill.md\\` and proceed with the task.\r\n\r\n**Example prompt for Documents skill:**\r\nIf you need to generate multi-format documentation, use this prompt:\r\n> \"Generate documentation with skill documents for [project-name]. Include:\r\n> - Concise overview (documentations/documentation.txt)\r\n> - Technical Markdown (documentations/documentation.md)\r\n> - Interactive HTML (documentations/documentation.html)\r\n> - Premium Documentation Landing Page (documentations/documentation-landing-page.html)\r\n> - CRITICAL: Save all files in the /documentations directory (create it if missing).\"\r\n\r\n**Dynamic Documentation Generation**:\r\nWhen generating documentation, do NOT simply fill a template. The Agent MUST:\r\n1. **Create** the \\`/documentations\\` directory if it does not exist.\r\n2. **Design** a custom layout and content structure suitable for the project type.\r\n3. **Synchronize** with the \\`ui-ux\\` skill for premium visual design (colors, typography, animations).\r\n4. **Scan All Specs**: If project-wide, read \\`heraspec/project.md\\` and all files in \\`heraspec/specs/\\` to synthesize the content.\r\n\r\n### Skill Discovery & Usage\r\n\r\n- List all skills: Check \\`heraspec/skills/\\` directory\r\n- Project-specific skills: \\`heraspec/skills/<project-type>/\\`\r\n- Cross-cutting skills: \\`heraspec/skills/<skill-name>/\\` (root level)\r\n- **Consistency**: Follow the step-by-step process in the skill's \\`skill.md\\`.\r\n\r\n### When Change Has Multiple Skills\r\n\r\n**Important**: Each task group uses ONE skill. When working on a task group, agent MUST use that skill's skill.md.\r\n\r\nExample with multiple skills in one change:\r\n\\`\\`\\`\r\n## 1. WordPress module \u2013 Feature (skill: admin-settings-page)\r\n- [ ] Task 1.1 Create module structure\r\n- [ ] Task 1.2 Configure registration\r\n\r\n## 2. UI/UX \u2013 Admin Interface (skill: ui-ux)\r\n- [ ] Task 2.1 Design color palette\r\n- [ ] Task 2.2 Create component styles\r\n\r\n## 3. Documents \u2013 User Guide (skill: documents)\r\n- [ ] Task 3.1 Write technical docs\r\n\\`\\`\\`\r\n\r\n**Key rule**: Switch skill.md when switching task groups!\r\n`;\r\n }\r\n\r\n static getConfigTemplate(): string {\r\n return `projectType: generic-webapp\r\nprojectName: \"HeraSpec Project\"\r\ndescription: \"A new project using HeraSpec\"\r\nskills: []\r\n`;\r\n }\r\n}\r\n", "/**\r\n * HeraSpec List Command\r\n * Lists changes or specs\r\n */\r\nimport path from 'path';\r\nimport { FileSystemUtils } from '../utils/file-system.js';\r\nimport { HERASPEC_DIR_NAME, CHANGES_DIR_NAME, SPECS_DIR_NAME, ARCHIVES_DIR_NAME } from './config.js';\r\n\r\nexport class ListCommand {\r\n async execute(\r\n targetPath: string = '.',\r\n mode: 'changes' | 'specs' = 'changes'\r\n ): Promise<void> {\r\n const heraspecPath = path.join(targetPath, HERASPEC_DIR_NAME);\r\n\r\n if (mode === 'changes') {\r\n await this.listChanges(heraspecPath);\r\n } else {\r\n await this.listSpecs(heraspecPath);\r\n }\r\n }\r\n\r\n private async listChanges(heraspecPath: string): Promise<void> {\r\n const changesDir = path.join(heraspecPath, CHANGES_DIR_NAME);\r\n\r\n try {\r\n await FileSystemUtils.stat(changesDir);\r\n } catch {\r\n console.log('No HeraSpec changes directory found. Run \"heraspec init\" first.');\r\n return;\r\n }\r\n\r\n const entries = await FileSystemUtils.readDirectory(changesDir);\r\n const changeDirs: string[] = [];\r\n\r\n for (const entry of entries) {\r\n const entryPath = path.join(changesDir, entry);\r\n const stats = await FileSystemUtils.stat(entryPath);\r\n if (stats.isDirectory() && entry !== ARCHIVES_DIR_NAME) {\r\n changeDirs.push(entry);\r\n }\r\n }\r\n\r\n if (changeDirs.length === 0) {\r\n console.log('No active changes found.');\r\n return;\r\n }\r\n\r\n changeDirs.sort();\r\n\r\n console.log('\\nActive changes:');\r\n console.log('\u2500'.repeat(50));\r\n for (const change of changeDirs) {\r\n console.log(` \u2022 ${change}`);\r\n }\r\n console.log();\r\n }\r\n\r\n private async listSpecs(heraspecPath: string): Promise<void> {\r\n const specsDir = path.join(heraspecPath, SPECS_DIR_NAME);\r\n\r\n try {\r\n await FileSystemUtils.stat(specsDir);\r\n } catch {\r\n console.log('No HeraSpec specs directory found. Run \"heraspec init\" first.');\r\n return;\r\n }\r\n\r\n const specs = await this.findSpecFiles(specsDir, '');\r\n\r\n if (specs.length === 0) {\r\n console.log('No specs found.');\r\n return;\r\n }\r\n\r\n specs.sort();\r\n\r\n console.log('\\nSpecs:');\r\n console.log('\u2500'.repeat(50));\r\n for (const spec of specs) {\r\n console.log(` \u2022 ${spec}`);\r\n }\r\n console.log();\r\n }\r\n\r\n private async findSpecFiles(dir: string, prefix: string): Promise<string[]> {\r\n const specs: string[] = [];\r\n const entries = await FileSystemUtils.readDirectory(dir);\r\n\r\n for (const entry of entries) {\r\n const entryPath = path.join(dir, entry);\r\n const stats = await FileSystemUtils.stat(entryPath);\r\n\r\n if (stats.isDirectory()) {\r\n const subSpecs = await this.findSpecFiles(\r\n entryPath,\r\n prefix ? `${prefix}/${entry}` : entry\r\n );\r\n specs.push(...subSpecs);\r\n } else if (entry === 'spec.md') {\r\n specs.push(prefix || 'global');\r\n }\r\n }\r\n\r\n return specs;\r\n }\r\n}\r\n\r\n", "/**\r\n * HeraSpec Archive Command\r\n * Archives a change and merges delta specs into source specs\r\n */\r\nimport path from 'path';\r\nimport ora from 'ora';\r\nimport fs from 'fs';\r\nimport { createHash } from 'crypto';\r\nimport chalk from 'chalk';\r\nimport { FileSystemUtils } from '../utils/file-system.js';\r\nimport {\r\n HERASPEC_DIR_NAME,\r\n CHANGES_DIR_NAME,\r\n ARCHIVES_DIR_NAME,\r\n SPECS_DIR_NAME,\r\n} from './config.js';\r\nimport { MarkdownParser } from './parsers/markdown-parser.js';\r\n\r\nexport class ArchiveCommand {\r\n async execute(changeName?: string, options?: { yes?: boolean }): Promise<void> {\r\n if (!changeName) {\r\n console.error('Error: Please specify a change name');\r\n console.log('Usage: heraspec archive <change-name> [--yes]');\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n const changePath = path.join('.', HERASPEC_DIR_NAME, CHANGES_DIR_NAME, changeName);\r\n\r\n if (!(await FileSystemUtils.fileExists(changePath))) {\r\n console.error(`Error: Change \"${changeName}\" not found`);\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n // Confirm if not --yes\r\n if (!options?.yes) {\r\n console.log(`\\nThis will archive \"${changeName}\" and merge delta specs into source specs.`);\r\n console.log('This action cannot be undone.\\n');\r\n // In a real implementation, you'd prompt here\r\n // For now, we'll require --yes flag\r\n console.error('Error: Please use --yes flag to confirm');\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n const spinner = ora({\r\n text: `Archiving change \"${changeName}\"...`,\r\n color: 'blue',\r\n }).start();\r\n\r\n try {\r\n // 1. Merge delta specs into source specs\r\n await this.mergeDeltaSpecs(changePath, changeName);\r\n\r\n // 2. Remove specs directory after merge (specs are now in source specs)\r\n const specsDir = path.join(\r\n '.',\r\n HERASPEC_DIR_NAME,\r\n SPECS_DIR_NAME,\r\n changeName\r\n );\r\n if (await FileSystemUtils.fileExists(specsDir)) {\r\n await FileSystemUtils.removeDirectory(specsDir, true);\r\n }\r\n\r\n // 3. Create archive directory with date prefix\r\n const archiveDir = path.join(\r\n '.',\r\n HERASPEC_DIR_NAME,\r\n CHANGES_DIR_NAME,\r\n ARCHIVES_DIR_NAME\r\n );\r\n await FileSystemUtils.createDirectory(archiveDir);\r\n\r\n const datePrefix = new Date().toISOString().split('T')[0];\r\n const archivePath = path.join(archiveDir, `${datePrefix}-${changeName}`);\r\n\r\n // 4. Move change to archive\r\n await FileSystemUtils.createDirectory(archivePath);\r\n await this.moveChangeToArchive(changePath, archivePath);\r\n\r\n // 5. Remove original change directory\r\n await FileSystemUtils.removeDirectory(changePath, true);\r\n\r\n spinner.succeed(chalk.green(`Change \"${changeName}\" archived successfully`));\r\n\r\n // 6. Auto-log to memory\r\n await this.autoLogToMemory(changeName, archivePath);\r\n\r\n } catch (error) {\r\n spinner.fail(chalk.red(`Error: ${(error as Error).message}`));\r\n throw error;\r\n }\r\n }\r\n\r\n private async mergeDeltaSpecs(changePath: string, changeName: string): Promise<void> {\r\n // Specs are now in heraspec/specs/<changeName>/ instead of heraspec/changes/<changeName>/specs/\r\n const deltaSpecsDir = path.join(\r\n '.',\r\n HERASPEC_DIR_NAME,\r\n SPECS_DIR_NAME,\r\n changeName\r\n );\r\n \r\n if (!(await FileSystemUtils.fileExists(deltaSpecsDir))) {\r\n return; // No delta specs to merge\r\n }\r\n\r\n const deltaSpecs = await this.findDeltaSpecFiles(deltaSpecsDir);\r\n\r\n for (const deltaSpec of deltaSpecs) {\r\n // Calculate relative path from specs/<changeName>/\r\n const relativePath = path.relative(deltaSpecsDir, deltaSpec.path);\r\n // Target is in specs/ (source of truth), maintaining the same relative path structure\r\n const targetSpecPath = path.join(\r\n '.',\r\n HERASPEC_DIR_NAME,\r\n SPECS_DIR_NAME,\r\n relativePath\r\n );\r\n\r\n // Read delta spec\r\n const deltaContent = await FileSystemUtils.readFile(deltaSpec.path);\r\n const parser = new MarkdownParser(deltaContent);\r\n const delta = parser.parseDeltaSpec(deltaContent);\r\n\r\n // Read or create target spec\r\n let targetContent = '';\r\n if (await FileSystemUtils.fileExists(targetSpecPath)) {\r\n targetContent = await FileSystemUtils.readFile(targetSpecPath);\r\n }\r\n\r\n // Read fingerprints\r\n const fingerprintsPath = path.join(changePath, 'fingerprints.json');\r\n let fingerprints: Record<string, string> = {};\r\n if (await FileSystemUtils.fileExists(fingerprintsPath)) {\r\n fingerprints = JSON.parse(await FileSystemUtils.readFile(fingerprintsPath));\r\n }\r\n\r\n // Validate fingerprints\r\n const reqs = [...delta.modified, ...delta.removed];\r\n for (const req of reqs) {\r\n const hashKey = `${relativePath}:${req.name}`;\r\n const expectedHash = fingerprints[hashKey];\r\n if (expectedHash) {\r\n const currentReqBlock = this.extractRequirementBlock(targetContent, req.name);\r\n const currentHash = currentReqBlock ? createHash('sha256').update(currentReqBlock).digest('hex') : null;\r\n \r\n if (currentHash !== expectedHash) {\r\n throw new Error(\r\n `Parallel Merge Conflict: The requirement \"${req.name}\" in ${relativePath} has been changed by someone else since you started this change.\\n` +\r\n `Please run \"heraspec sync ${changeName}\" to update your base and resolve the conflict.`\r\n );\r\n }\r\n }\r\n }\r\n\r\n // Merge delta into target\r\n const mergedContent = this.mergeDeltaIntoSpec(targetContent, delta, deltaSpec.name);\r\n\r\n // Ensure directory exists\r\n await FileSystemUtils.createDirectory(path.dirname(targetSpecPath));\r\n\r\n // Write merged spec\r\n await FileSystemUtils.writeFile(targetSpecPath, mergedContent);\r\n }\r\n }\r\n\r\n private mergeDeltaIntoSpec(\r\n existingContent: string,\r\n delta: { added: any[]; modified: any[]; removed: any[] },\r\n specName: string\r\n ): string {\r\n let merged = existingContent || `# Spec: ${specName}\\n\\n## Purpose\\n\\n## Requirements\\n\\n`;\r\n\r\n // Process removed\r\n if (delta.removed && delta.removed.length > 0) {\r\n for (const req of delta.removed) {\r\n merged = this.modifyRequirementBlock(merged, req.name, null);\r\n }\r\n }\r\n\r\n // Process modified\r\n if (delta.modified && delta.modified.length > 0) {\r\n for (const req of delta.modified) {\r\n const newBlock = this.stringifyRequirement(req);\r\n merged = this.modifyRequirementBlock(merged, req.name, newBlock);\r\n }\r\n }\r\n\r\n // Add new requirements\r\n if (delta.added && delta.added.length > 0) {\r\n for (const req of delta.added) {\r\n const newBlock = this.stringifyRequirement(req);\r\n merged += `\\n${newBlock}`;\r\n }\r\n }\r\n\r\n return merged;\r\n }\r\n\r\n private modifyRequirementBlock(content: string, reqName: string, newContent: string | null): string {\r\n const escapedName = reqName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n const reqRegex = new RegExp(`###\\\\s+Requirement:\\\\s*${escapedName}\\\\s*\\\\n([\\\\s\\\\S]*?)(?=(?:###\\\\s+Requirement:|$))`, 'i');\r\n \r\n if (newContent === null) {\r\n return content.replace(reqRegex, '');\r\n } else {\r\n if (reqRegex.test(content)) {\r\n return content.replace(reqRegex, newContent);\r\n } else {\r\n return content + '\\\\n' + newContent;\r\n }\r\n }\r\n }\r\n\r\n private extractRequirementBlock(content: string, reqName: string): string | null {\r\n const escapedName = reqName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n const reqRegex = new RegExp(`###\\\\s+Requirement:\\\\s*${escapedName}\\\\s*\\\\n([\\\\s\\\\S]*?)(?=(?:###\\\\s+Requirement:|$))`, 'i');\r\n const match = content.match(reqRegex);\r\n return match ? match[0].trim() : null;\r\n }\r\n\r\n private stringifyRequirement(req: any): string {\r\n let str = `### Requirement: ${req.name}\\n${req.description}\\n\\n`;\r\n if (req.scenarios && req.scenarios.length > 0) {\r\n for (const sc of req.scenarios) {\r\n str += `#### Scenario: ${sc.name}\\n`;\r\n for (const step of sc.steps) {\r\n str += `- ${step}\\n`;\r\n }\r\n str += `\\n`;\r\n }\r\n }\r\n return str;\r\n }\r\n\r\n private async moveChangeToArchive(sourcePath: string, archivePath: string): Promise<void> {\r\n const entries = await FileSystemUtils.readDirectory(sourcePath);\r\n\r\n for (const entry of entries) {\r\n const sourceEntry = path.join(sourcePath, entry);\r\n const archiveEntry = path.join(archivePath, entry);\r\n const stats = await FileSystemUtils.stat(sourceEntry);\r\n\r\n if (stats.isDirectory()) {\r\n await FileSystemUtils.createDirectory(archiveEntry);\r\n await this.moveChangeToArchive(sourceEntry, archiveEntry);\r\n } else {\r\n await FileSystemUtils.moveFile(sourceEntry, archiveEntry);\r\n }\r\n }\r\n }\r\n\r\n private async findDeltaSpecFiles(\r\n dir: string,\r\n prefix = ''\r\n ): Promise<Array<{ name: string; path: string }>> {\r\n const specs: Array<{ name: string; path: string }> = [];\r\n const entries = await FileSystemUtils.readDirectory(dir);\r\n\r\n for (const entry of entries) {\r\n const entryPath = path.join(dir, entry);\r\n const stats = await FileSystemUtils.stat(entryPath);\r\n\r\n if (stats.isDirectory()) {\r\n const subSpecs = await this.findDeltaSpecFiles(\r\n entryPath,\r\n prefix ? `${prefix}/${entry}` : entry\r\n );\r\n specs.push(...subSpecs);\r\n } else if (entry.endsWith('.md')) {\r\n specs.push({\r\n name: prefix || path.basename(entry, '.md'),\r\n path: entryPath,\r\n });\r\n }\r\n }\r\n\r\n return specs;\r\n }\r\n private async autoLogToMemory(changeName: string, archivePath: string): Promise<void> {\r\n try {\r\n // Check if memory is enabled/initialized\r\n const memoryDbPath = path.join('.', HERASPEC_DIR_NAME, 'memory', 'heraspec-memory.db');\r\n if (!(await FileSystemUtils.fileExists(memoryDbPath))) {\r\n // Memory system not initialized, skip auto-logging silently\r\n return;\r\n }\r\n\r\n // Dynamically import MemoryCommand to avoid circular dependencies if any\r\n const { MemoryCommand } = await import('../commands/memory.js');\r\n const memoryCmd = new MemoryCommand();\r\n\r\n // Read proposal content if exists\r\n let narrative = '';\r\n const proposalPath = path.join(archivePath, 'proposal.md');\r\n if (await FileSystemUtils.fileExists(proposalPath)) {\r\n narrative = await FileSystemUtils.readFile(proposalPath);\r\n }\r\n\r\n // Also grab tasks if available\r\n const tasksPath = path.join(archivePath, 'tasks.md');\r\n if (await FileSystemUtils.fileExists(tasksPath)) {\r\n const tasksContent = await FileSystemUtils.readFile(tasksPath);\r\n if (narrative) narrative += '\\n\\n---\\n\\n';\r\n narrative += tasksContent;\r\n }\r\n\r\n // Truncate narrative if too long to prevent token blowout\r\n const MAX_LENGTH = 10000;\r\n if (narrative.length > MAX_LENGTH) {\r\n narrative = narrative.substring(0, MAX_LENGTH) + '\\n...[truncated]';\r\n }\r\n\r\n // We call log silently by capturing console.log temporarily or we can just call it\r\n // Wait, memoryCmd.log calls spinner.succeed and console.log, which is fine since we want to inform the user\r\n // But maybe we don't want spinner if we just succeeded. The log method uses its own spinner.\r\n \r\n // Call memoryCmd.log\r\n await memoryCmd.log({\r\n type: 'feature',\r\n title: `Archived change: ${changeName}`,\r\n narrative: narrative || `Auto-archived change: ${changeName}`,\r\n // We could theoretically set discoveryTokens here, but auto-log uses 0.\r\n discoveryTokens: '0'\r\n }, '.');\r\n\r\n } catch (error) {\r\n // Silently fail if something goes wrong with memory auto-logging\r\n // We don't want to break the archive process\r\n }\r\n }\r\n}\r\n\r\n", "/**\r\n * Markdown Parser for HeraSpec\r\n * Handles parsing of specs with Meta section, project types, and delta specs\r\n */\r\nimport { z } from 'zod';\r\nimport { Spec, RequirementSchema } from '../schemas/index.js';\r\nimport { SpecMeta } from '../config.js';\r\n\r\ninterface Section {\r\n level: number;\r\n title: string;\r\n content: string[];\r\n}\r\n\r\nexport class MarkdownParser {\r\n private lines: string[];\r\n\r\n constructor(content: string) {\r\n this.lines = MarkdownParser.normalizeContent(content).split('\\n');\r\n }\r\n\r\n protected static normalizeContent(content: string): string {\r\n return content.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\r\n }\r\n\r\n parseSpec(name: string): Spec {\r\n const sections = this.parseSections();\r\n const meta = this.parseMeta(sections);\r\n const purpose = this.findSection(sections, 'Purpose')?.content.join('\\n').trim() || '';\r\n const requirementsSection = this.findSection(sections, 'Requirements');\r\n\r\n if (!purpose) {\r\n throw new Error('Spec must have a Purpose section');\r\n }\r\n\r\n if (!requirementsSection) {\r\n throw new Error('Spec must have a Requirements section');\r\n }\r\n\r\n const requirements = this.parseRequirements(requirementsSection);\r\n\r\n return {\r\n name,\r\n meta,\r\n overview: purpose.trim(),\r\n requirements,\r\n metadata: {\r\n version: '1.0.0',\r\n format: 'heraspec',\r\n },\r\n };\r\n }\r\n\r\n parseDeltaSpec(content: string): {\r\n added: any[];\r\n modified: any[];\r\n removed: any[];\r\n } {\r\n const sections = this.parseSections();\r\n const added = this.findSection(sections, 'ADDED Requirements');\r\n const modified = this.findSection(sections, 'MODIFIED Requirements');\r\n const removed = this.findSection(sections, 'REMOVED Requirements');\r\n\r\n return {\r\n added: added ? this.parseDeltaRequirements(added) : [],\r\n modified: modified ? this.parseDeltaRequirements(modified) : [],\r\n removed: removed ? this.parseDeltaRequirements(removed) : [],\r\n };\r\n }\r\n\r\n private parseMeta(sections: Section[]): SpecMeta | undefined {\r\n const metaSection = this.findSection(sections, 'Meta');\r\n if (!metaSection) {\r\n return undefined;\r\n }\r\n\r\n const meta: SpecMeta = {};\r\n const content = metaSection.content.join('\\n');\r\n\r\n // Parse project type\r\n const projectTypeMatch = content.match(/project type:\\s*(.+)/i);\r\n if (projectTypeMatch) {\r\n const types = projectTypeMatch[1].split('|').map(t => t.trim());\r\n meta.projectType = types.length === 1 ? types[0] : types;\r\n }\r\n\r\n // Parse domain\r\n const domainMatch = content.match(/domain:\\s*(.+)/i);\r\n if (domainMatch) {\r\n meta.domain = domainMatch[1].trim();\r\n }\r\n\r\n // Parse stack\r\n const stackMatch = content.match(/stack:\\s*(.+)/i);\r\n if (stackMatch) {\r\n const stacks = stackMatch[1].split('|').map(s => s.trim());\r\n meta.stack = stacks.length === 1 ? stacks[0] : stacks;\r\n }\r\n\r\n return Object.keys(meta).length > 0 ? meta : undefined;\r\n }\r\n\r\n private parseSections(): Section[] {\r\n const sections: Section[] = [];\r\n let currentSection: Section | null = null;\r\n\r\n for (const line of this.lines) {\r\n const headerMatch = line.match(/^(#{1,6})\\s+(.+)$/);\r\n if (headerMatch) {\r\n if (currentSection) {\r\n sections.push(currentSection);\r\n }\r\n currentSection = {\r\n level: headerMatch[1].length,\r\n title: headerMatch[2].trim(),\r\n content: [],\r\n };\r\n } else if (currentSection) {\r\n currentSection.content.push(line);\r\n }\r\n }\r\n\r\n if (currentSection) {\r\n sections.push(currentSection);\r\n }\r\n\r\n return sections;\r\n }\r\n\r\n private findSection(sections: Section[], title: string): Section | undefined {\r\n return sections.find(s => \r\n s.title.toLowerCase() === title.toLowerCase() ||\r\n s.title.toLowerCase().includes(title.toLowerCase())\r\n );\r\n }\r\n\r\n private parseRequirements(section: Section): z.infer<typeof RequirementSchema>[] {\r\n const requirements: z.infer<typeof RequirementSchema>[] = [];\r\n const lines = section.content;\r\n\r\n let currentRequirement: {\r\n name: string;\r\n description: string;\r\n scenarios: any[];\r\n constraints?: string[];\r\n } | null = null;\r\n\r\n let inRequirement = false;\r\n let inScenario = false;\r\n let currentScenario: { name: string; steps: string[] } | null = null;\r\n\r\n for (let i = 0; i < lines.length; i++) {\r\n const line = lines[i];\r\n\r\n // Check for requirement header\r\n const reqMatch = line.match(/^###\\s+Requirement:\\s*(.+)$/i);\r\n if (reqMatch) {\r\n if (currentRequirement) {\r\n requirements.push(currentRequirement as any);\r\n }\r\n currentRequirement = {\r\n name: reqMatch[1].trim(),\r\n description: '',\r\n scenarios: [],\r\n };\r\n inRequirement = true;\r\n continue;\r\n }\r\n\r\n // Check for scenario header\r\n const scenarioMatch = line.match(/^####\\s+Scenario:\\s*(.+)$/i);\r\n if (scenarioMatch && currentRequirement) {\r\n if (currentScenario) {\r\n currentRequirement.scenarios.push(currentScenario);\r\n }\r\n currentScenario = {\r\n name: scenarioMatch[1].trim(),\r\n steps: [],\r\n };\r\n inScenario = true;\r\n continue;\r\n }\r\n\r\n // Check for GIVEN/WHEN/THEN steps\r\n if (currentScenario && (line.match(/^-\\s*(GIVEN|WHEN|THEN|AND|BUT)\\s+/i))) {\r\n const step = line.replace(/^-\\s*/, '').trim();\r\n currentScenario.steps.push(step);\r\n continue;\r\n }\r\n\r\n // Regular content line\r\n if (currentRequirement && !inScenario) {\r\n const trimmed = line.trim();\r\n if (trimmed && !trimmed.startsWith('#')) {\r\n currentRequirement.description += (currentRequirement.description ? '\\n' : '') + trimmed;\r\n }\r\n }\r\n }\r\n\r\n // Add final requirement and scenario\r\n if (currentScenario && currentRequirement) {\r\n currentRequirement.scenarios.push(currentScenario);\r\n }\r\n if (currentRequirement) {\r\n requirements.push(currentRequirement as any);\r\n }\r\n\r\n return requirements;\r\n }\r\n\r\n private parseDeltaRequirements(section: Section): any[] {\r\n // Similar to parseRequirements but expects ADDED/MODIFIED/REMOVED markers\r\n return this.parseRequirements(section);\r\n }\r\n}\r\n\r\n", "/**\r\n * HeraSpec Sync Command\r\n * Syncs a change with its base source specs (Rebasing)\r\n */\r\nimport path from 'path';\r\nimport chalk from 'chalk';\r\nimport ora from 'ora';\r\nimport { createHash } from 'crypto';\r\nimport { FileSystemUtils } from '../utils/file-system.js';\r\nimport { MarkdownParser } from './parsers/markdown-parser.js';\r\nimport { HERASPEC_DIR_NAME, CHANGES_DIR_NAME, SPECS_DIR_NAME } from './config.js';\r\nimport { readFileSync } from 'fs';\r\n\r\nexport class SyncCommand {\r\n async execute(changeName?: string): Promise<void> {\r\n if (!changeName) {\r\n console.error('Error: Please specify a change name to sync');\r\n console.log('Usage: heraspec sync <change-name>');\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n const changePath = path.join('.', HERASPEC_DIR_NAME, CHANGES_DIR_NAME, changeName);\r\n if (!(await FileSystemUtils.fileExists(changePath))) {\r\n console.error(`Error: Change \"${changeName}\" not found at ${changePath}`);\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n const spinner = ora(`Syncing fingerprints for \"${changeName}\"...`).start();\r\n\r\n try {\r\n const fingerprintsPath = path.join(changePath, 'fingerprints.json');\r\n let fingerprints: Record<string, string> = {};\r\n \r\n if (await FileSystemUtils.fileExists(fingerprintsPath)) {\r\n fingerprints = JSON.parse(readFileSync(fingerprintsPath, 'utf-8'));\r\n } else {\r\n spinner.info(chalk.blue(`No fingerprints.json found for \"${changeName}\". Run 'heraspec validate ${changeName}' to capture initial fingerprints.`));\r\n return;\r\n }\r\n\r\n const specsDir = path.join('.', HERASPEC_DIR_NAME, SPECS_DIR_NAME);\r\n const deltaSpecsDir = path.join(specsDir, changeName);\r\n \r\n if (!(await FileSystemUtils.fileExists(deltaSpecsDir))) {\r\n spinner.info(chalk.yellow(`No delta specs found for \"${changeName}\". Nothing to sync.`));\r\n return;\r\n }\r\n\r\n const deltaSpecs = await this.findDeltaSpecs(deltaSpecsDir);\r\n let updatedCount = 0;\r\n\r\n for (const specPath of deltaSpecs) {\r\n const relativePath = path.relative(path.resolve(deltaSpecsDir), path.resolve(specPath));\r\n const sourceSpecPath = path.join(path.resolve(specsDir), relativePath);\r\n \r\n let sourceContent = '';\r\n if (await FileSystemUtils.fileExists(sourceSpecPath)) {\r\n sourceContent = readFileSync(sourceSpecPath, 'utf-8');\r\n }\r\n\r\n const deltaContent = readFileSync(specPath, 'utf-8');\r\n const parser = new MarkdownParser(deltaContent);\r\n const delta = parser.parseDeltaSpec(deltaContent);\r\n const reqs = [...delta.modified, ...delta.removed];\r\n\r\n for (const req of reqs) {\r\n const hashKey = `${relativePath}:${req.name}`;\r\n const expectedHash = fingerprints[hashKey];\r\n \r\n if (expectedHash) {\r\n const currentReqBlock = this.extractRequirementBlock(sourceContent, req.name);\r\n const currentHash = currentReqBlock ? createHash('sha256').update(currentReqBlock).digest('hex') : null;\r\n \r\n if (currentHash && currentHash !== expectedHash) {\r\n spinner.stop();\r\n console.log(chalk.yellow(`\\n\u26A0\uFE0F Conflict detected for requirement \"${req.name}\" in ${relativePath}`));\r\n console.log(chalk.gray(`Source spec was updated after your change started.`));\r\n \r\n // Auto-sync by updating the fingerprint\r\n fingerprints[hashKey] = currentHash;\r\n updatedCount++;\r\n \r\n console.log(chalk.green(`\u2713 Fingerprint updated. Please review the delta spec to ensure your modifications still apply correctly to the new source.`));\r\n spinner.start();\r\n } else if (!currentHash) {\r\n spinner.stop();\r\n console.log(chalk.red(`\\n\u274C Requirement \"${req.name}\" no longer exists in source spec ${relativePath}!`));\r\n console.log(chalk.gray(`You should probably remove this requirement from your delta spec.`));\r\n spinner.start();\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (updatedCount > 0) {\r\n await FileSystemUtils.writeFile(fingerprintsPath, JSON.stringify(fingerprints, null, 2));\r\n spinner.succeed(chalk.green(`Synced ${updatedCount} fingerprint(s) successfully.`));\r\n } else {\r\n spinner.succeed(chalk.green('Already up to date. No conflicts detected.'));\r\n }\r\n } catch (error) {\r\n spinner.fail(chalk.red(`Error: ${(error as Error).message}`));\r\n process.exitCode = 1;\r\n }\r\n }\r\n\r\n private async findDeltaSpecs(dir: string): Promise<string[]> {\r\n const specs: string[] = [];\r\n const entries = await FileSystemUtils.readDirectory(dir);\r\n\r\n for (const entry of entries) {\r\n const entryPath = path.join(dir, entry);\r\n const stats = await FileSystemUtils.stat(entryPath);\r\n\r\n if (stats.isDirectory()) {\r\n const subSpecs = await this.findDeltaSpecs(entryPath);\r\n specs.push(...subSpecs);\r\n } else if (entry.endsWith('.md')) {\r\n specs.push(entryPath);\r\n }\r\n }\r\n\r\n return specs;\r\n }\r\n\r\n private extractRequirementBlock(content: string, reqName: string): string | null {\r\n const escapedName = reqName.replace(/[.*+?^${}()|[\\\\]\\\\\\\\]/g, '\\\\\\$&');\r\n const reqRegex = new RegExp(`###\\\\S+Requirement:\\\\S*${escapedName}\\\\S*\\\\\\\\n([\\\\S\\\\S]*?)(?=(?:###\\\\S+Requirement:|$))`, 'i');\r\n const match = content.match(reqRegex);\r\n return match ? match[0].trim() : null;\r\n }\r\n}\r\n", "/**\r\n * HeraSpec Restore Command\r\n * Restores an archived change back to active changes\r\n */\r\nimport path from 'path';\r\nimport ora from 'ora';\r\nimport chalk from 'chalk';\r\nimport { FileSystemUtils } from '../utils/file-system.js';\r\nimport {\r\n HERASPEC_DIR_NAME,\r\n CHANGES_DIR_NAME,\r\n ARCHIVES_DIR_NAME,\r\n} from './config.js';\r\n\r\nexport class RestoreCommand {\r\n async execute(archiveName?: string, options?: { yes?: boolean }): Promise<void> {\r\n const archivesDir = path.join(\r\n '.',\r\n HERASPEC_DIR_NAME,\r\n CHANGES_DIR_NAME,\r\n ARCHIVES_DIR_NAME\r\n );\r\n\r\n // Check if archives directory exists\r\n if (!(await FileSystemUtils.fileExists(archivesDir))) {\r\n console.error('Error: No archives directory found. No archives to restore.');\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n // List available archives if name not provided\r\n if (!archiveName) {\r\n const archives = await this.listArchives(archivesDir);\r\n if (archives.length === 0) {\r\n console.log('No archived changes found.');\r\n return;\r\n }\r\n\r\n console.log('\\nAvailable archives:');\r\n console.log('\u2500'.repeat(60));\r\n archives.forEach((archive, index) => {\r\n console.log(`${index + 1}. ${archive}`);\r\n });\r\n console.log();\r\n console.error('Error: Please specify archive name to restore');\r\n console.log(`Usage: heraspec restore <archive-name>`);\r\n console.log(`Example: heraspec restore 2025-01-15-add-two-factor-auth`);\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n const archivePath = path.join(archivesDir, archiveName);\r\n\r\n // Check if archive exists\r\n if (!(await FileSystemUtils.fileExists(archivePath))) {\r\n console.error(`Error: Archive \"${archiveName}\" not found`);\r\n console.log('\\nAvailable archives:');\r\n const archives = await this.listArchives(archivesDir);\r\n archives.forEach((archive) => {\r\n console.log(` - ${archive}`);\r\n });\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n // Extract change name (remove date prefix)\r\n const changeName = this.extractChangeName(archiveName);\r\n const changePath = path.join(\r\n '.',\r\n HERASPEC_DIR_NAME,\r\n CHANGES_DIR_NAME,\r\n changeName\r\n );\r\n\r\n // Check if change already exists\r\n if (await FileSystemUtils.fileExists(changePath)) {\r\n console.error(`Error: Change \"${changeName}\" already exists in active changes.`);\r\n console.log('Please remove or rename the existing change first.');\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n // Confirm if not --yes\r\n if (!options?.yes) {\r\n console.log(`\\nThis will restore archive \"${archiveName}\" to active change \"${changeName}\".`);\r\n console.log('Note: This will not revert spec changes that were merged during archive.\\n');\r\n console.error('Error: Please use --yes flag to confirm');\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n const spinner = ora({\r\n text: `Restoring archive \"${archiveName}\"...`,\r\n color: 'blue',\r\n }).start();\r\n\r\n try {\r\n // Ensure changes directory exists\r\n const changesDir = path.join(\r\n '.',\r\n HERASPEC_DIR_NAME,\r\n CHANGES_DIR_NAME\r\n );\r\n await FileSystemUtils.createDirectory(changesDir);\r\n \r\n // Create destination directory first\r\n await FileSystemUtils.createDirectory(changePath);\r\n \r\n // Move archive back to changes directory\r\n await this.moveArchiveToChanges(archivePath, changePath);\r\n\r\n // Remove archive directory\r\n await FileSystemUtils.removeDirectory(archivePath, true);\r\n\r\n spinner.succeed(\r\n chalk.green(`Archive \"${archiveName}\" restored successfully to \"${changeName}\"`)\r\n );\r\n console.log();\r\n console.log(chalk.cyan('Note:'));\r\n console.log(\r\n chalk.gray(\r\n 'Spec changes that were merged during archive are still in source specs.'\r\n )\r\n );\r\n console.log(\r\n chalk.gray(\r\n 'You may need to manually review and revert spec changes if needed.'\r\n )\r\n );\r\n } catch (error) {\r\n spinner.fail(chalk.red(`Error: ${(error as Error).message}`));\r\n throw error;\r\n }\r\n }\r\n\r\n private async listArchives(archivesDir: string): Promise<string[]> {\r\n const archives: string[] = [];\r\n const entries = await FileSystemUtils.readDirectory(archivesDir);\r\n\r\n for (const entry of entries) {\r\n const entryPath = path.join(archivesDir, entry);\r\n const stats = await FileSystemUtils.stat(entryPath);\r\n if (stats.isDirectory()) {\r\n archives.push(entry);\r\n }\r\n }\r\n\r\n return archives.sort();\r\n }\r\n\r\n private extractChangeName(archiveName: string): string {\r\n // Remove date prefix (YYYY-MM-DD-)\r\n // Example: \"2025-01-15-add-two-factor-auth\" -> \"add-two-factor-auth\"\r\n const datePattern = /^\\d{4}-\\d{2}-\\d{2}-/;\r\n return archiveName.replace(datePattern, '');\r\n }\r\n\r\n private async moveArchiveToChanges(sourcePath: string, destPath: string): Promise<void> {\r\n const entries = await FileSystemUtils.readDirectory(sourcePath);\r\n\r\n for (const entry of entries) {\r\n const sourceEntry = path.join(sourcePath, entry);\r\n const destEntry = path.join(destPath, entry);\r\n const stats = await FileSystemUtils.stat(sourceEntry);\r\n\r\n if (stats.isDirectory()) {\r\n await FileSystemUtils.createDirectory(destEntry);\r\n await this.moveArchiveToChanges(sourceEntry, destEntry);\r\n } else {\r\n await FileSystemUtils.moveFile(sourceEntry, destEntry);\r\n }\r\n }\r\n }\r\n}\r\n\r\n", "/**\r\n * HeraSpec Show Command\r\n * Shows a change or spec in readable format\r\n */\r\nimport path from 'path';\r\nimport { readFileSync } from 'fs';\r\nimport chalk from 'chalk';\r\nimport { FileSystemUtils } from '../utils/file-system.js';\r\nimport { TaskParser } from '../utils/task-parser.js';\r\nimport {\r\n HERASPEC_DIR_NAME,\r\n CHANGES_DIR_NAME,\r\n SPECS_DIR_NAME,\r\n HERASPEC_MARKERS,\r\n} from '../core/config.js';\r\n\r\nexport class ShowCommand {\r\n async execute(itemName?: string): Promise<void> {\r\n if (!itemName) {\r\n console.error('Error: Please specify a change or spec name');\r\n console.log('Usage: heraspec show <change-name>');\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n // Try to find as change first\r\n const changePath = path.join(\r\n '.',\r\n HERASPEC_DIR_NAME,\r\n CHANGES_DIR_NAME,\r\n itemName\r\n );\r\n\r\n if (await FileSystemUtils.fileExists(changePath)) {\r\n await this.showChange(itemName, changePath);\r\n return;\r\n }\r\n\r\n // Try to find as spec\r\n const specPath = this.findSpecPath(itemName);\r\n if (specPath && (await FileSystemUtils.fileExists(specPath))) {\r\n await this.showSpec(specPath);\r\n return;\r\n }\r\n\r\n console.error(`Error: Change or spec \"${itemName}\" not found`);\r\n process.exitCode = 1;\r\n }\r\n\r\n private async showChange(changeName: string, changePath: string): Promise<void> {\r\n console.log(`\\n\uD83D\uDCCB Change: ${changeName}\\n`);\r\n console.log('\u2550'.repeat(60));\r\n\r\n // Show proposal\r\n const proposalPath = path.join(changePath, HERASPEC_MARKERS.PROPOSAL_MD);\r\n if (await FileSystemUtils.fileExists(proposalPath)) {\r\n console.log('\\n## Proposal\\n');\r\n const proposal = await FileSystemUtils.readFile(proposalPath);\r\n console.log(proposal);\r\n }\r\n\r\n // Show tasks\r\n const tasksPath = path.join(changePath, HERASPEC_MARKERS.TASKS_MD);\r\n if (await FileSystemUtils.fileExists(tasksPath)) {\r\n console.log('\\n## Tasks\\n');\r\n const tasks = await FileSystemUtils.readFile(tasksPath);\r\n console.log(tasks);\r\n\r\n // Show skills used in tasks\r\n try {\r\n const parsedTasks = TaskParser.parseTasks(tasksPath);\r\n if (parsedTasks.skillsUsed.length > 0) {\r\n console.log('\\n## Skills Used in This Change\\n');\r\n for (const skillInfo of parsedTasks.skillsUsed) {\r\n if (skillInfo.skill) {\r\n const skillLabel = skillInfo.projectType \r\n ? `${skillInfo.projectType}/${skillInfo.skill}`\r\n : skillInfo.skill;\r\n console.log(chalk.cyan(` \u2022 ${skillLabel}`));\r\n console.log(chalk.gray(` Location: heraspec/skills/${skillInfo.projectType ? skillInfo.projectType + '/' : ''}${skillInfo.skill}/`));\r\n }\r\n }\r\n console.log();\r\n console.log(chalk.yellow('\uD83D\uDCA1 Tip: Read skill.md files to understand how to implement tasks.'));\r\n console.log();\r\n }\r\n } catch (error) {\r\n // Ignore parsing errors\r\n }\r\n }\r\n\r\n // Show design if exists\r\n const designPath = path.join(changePath, HERASPEC_MARKERS.DESIGN_MD);\r\n if (await FileSystemUtils.fileExists(designPath)) {\r\n console.log('\\n## Design\\n');\r\n const design = await FileSystemUtils.readFile(designPath);\r\n console.log(design);\r\n }\r\n\r\n // Show delta specs (now in heraspec/specs/<changeName>/ instead of heraspec/changes/<changeName>/specs/)\r\n const specsPath = path.join(\r\n '.',\r\n HERASPEC_DIR_NAME,\r\n SPECS_DIR_NAME,\r\n changeName\r\n );\r\n if (await FileSystemUtils.fileExists(specsPath)) {\r\n const deltaSpecs = await this.findDeltaSpecs(specsPath);\r\n if (deltaSpecs.length > 0) {\r\n console.log('\\n## Delta Specs\\n');\r\n for (const spec of deltaSpecs) {\r\n console.log(`\\n### ${spec.name}\\n`);\r\n const content = await FileSystemUtils.readFile(spec.path);\r\n console.log(content);\r\n }\r\n }\r\n }\r\n\r\n console.log('\\n' + '\u2550'.repeat(60) + '\\n');\r\n }\r\n\r\n private async showSpec(specPath: string): Promise<void> {\r\n console.log('\\n\uD83D\uDCC4 Spec\\n');\r\n console.log('\u2550'.repeat(60));\r\n const content = await FileSystemUtils.readFile(specPath);\r\n console.log(content);\r\n console.log('\u2550'.repeat(60) + '\\n');\r\n }\r\n\r\n private findSpecPath(specName: string): string | null {\r\n // Try various path formats\r\n const basePath = path.join('.', HERASPEC_DIR_NAME, SPECS_DIR_NAME);\r\n const paths = [\r\n path.join(basePath, `${specName}.md`),\r\n path.join(basePath, specName, 'spec.md'),\r\n path.join(basePath, ...specName.split('/'), 'spec.md'),\r\n ];\r\n\r\n // Return first potential path (caller will check existence)\r\n return paths[0];\r\n }\r\n\r\n private async findDeltaSpecs(dir: string, prefix = ''): Promise<Array<{ name: string; path: string }>> {\r\n const specs: Array<{ name: string; path: string }> = [];\r\n const entries = await FileSystemUtils.readDirectory(dir);\r\n\r\n for (const entry of entries) {\r\n const entryPath = path.join(dir, entry);\r\n const stats = await FileSystemUtils.stat(entryPath);\r\n\r\n if (stats.isDirectory()) {\r\n const subSpecs = await this.findDeltaSpecs(\r\n entryPath,\r\n prefix ? `${prefix}/${entry}` : entry\r\n );\r\n specs.push(...subSpecs);\r\n } else if (entry === 'spec.md' || entry.endsWith('.md')) {\r\n specs.push({\r\n name: prefix || 'global',\r\n path: entryPath,\r\n });\r\n }\r\n }\r\n\r\n return specs;\r\n }\r\n}\r\n\r\n", "/**\r\n * Task Parser\r\n * Parses tasks.md to extract skill information\r\n */\r\nimport { readFileSync } from 'fs';\r\nimport { SkillManager } from '../core/skills/index.js';\r\n\r\nexport interface TaskGroup {\r\n title: string;\r\n projectType?: string;\r\n skill?: string;\r\n tasks: Array<{\r\n id: string;\r\n description: string;\r\n completed: boolean;\r\n }>;\r\n}\r\n\r\nexport interface ParsedTasks {\r\n groups: TaskGroup[];\r\n skillsUsed: Array<{ projectType?: string; skill: string }>;\r\n}\r\n\r\nexport class TaskParser {\r\n static parseTasks(filePath: string): ParsedTasks {\r\n const content = readFileSync(filePath, 'utf-8');\r\n const lines = content.split('\\n');\r\n\r\n const groups: TaskGroup[] = [];\r\n const skillsUsed = new Set<string>();\r\n let currentGroup: TaskGroup | null = null;\r\n\r\n for (const line of lines) {\r\n // Match task group header: ## 1. Title (projectType: xxx, skill: yyy)\r\n const groupMatch = line.match(/^##+\\s+\\d+\\.\\s+(.+?)\\s*\\((.+)\\)/);\r\n \r\n if (groupMatch) {\r\n // Save previous group\r\n if (currentGroup) {\r\n groups.push(currentGroup);\r\n }\r\n\r\n const title = groupMatch[1].trim();\r\n const params = groupMatch[2];\r\n \r\n // Extract projectType and skill\r\n const skillInfo = SkillManager.extractSkillFromTask(`(${params})`);\r\n \r\n currentGroup = {\r\n title,\r\n projectType: skillInfo?.projectType,\r\n skill: skillInfo?.skill,\r\n tasks: [],\r\n };\r\n\r\n if (skillInfo?.skill) {\r\n const skillKey = skillInfo.projectType \r\n ? `${skillInfo.projectType}:${skillInfo.skill}`\r\n : skillInfo.skill;\r\n skillsUsed.add(skillKey);\r\n }\r\n continue;\r\n }\r\n\r\n // Match task: - [ ] or - [x]\r\n const taskMatch = line.match(/^-\\s+\\[([ x])\\]\\s+(.+)/);\r\n if (taskMatch && currentGroup) {\r\n const completed = taskMatch[1] === 'x';\r\n const description = taskMatch[2].trim();\r\n \r\n // Extract task ID if present (e.g., \"1.1 Task description\")\r\n const idMatch = description.match(/^(\\d+\\.\\d+)\\s+/);\r\n const id = idMatch ? idMatch[1] : `${currentGroup.tasks.length + 1}`;\r\n const taskDesc = idMatch ? description.replace(/^\\d+\\.\\d+\\s+/, '') : description;\r\n\r\n currentGroup.tasks.push({\r\n id,\r\n description: taskDesc,\r\n completed,\r\n });\r\n }\r\n }\r\n\r\n // Save last group\r\n if (currentGroup) {\r\n groups.push(currentGroup);\r\n }\r\n\r\n // Convert skillsUsed set to array\r\n const skillsArray = Array.from(skillsUsed).map(skillKey => {\r\n const [projectType, skill] = skillKey.includes(':') \r\n ? skillKey.split(':')\r\n : [undefined, skillKey];\r\n return { projectType, skill };\r\n });\r\n\r\n return {\r\n groups,\r\n skillsUsed: skillsArray,\r\n };\r\n }\r\n\r\n static async getSkillsForTasks(filePath: string): Promise<Array<{ projectType?: string; skill: string; path: string }>> {\r\n const parsed = this.parseTasks(filePath);\r\n const skills: Array<{ projectType?: string; skill: string; path: string }> = [];\r\n\r\n for (const skillInfo of parsed.skillsUsed) {\r\n if (skillInfo.skill) {\r\n const skillPath = await SkillManager.findSkillPath(\r\n skillInfo.projectType || '',\r\n skillInfo.skill,\r\n '.'\r\n );\r\n \r\n if (skillPath) {\r\n skills.push({\r\n projectType: skillInfo.projectType,\r\n skill: skillInfo.skill,\r\n path: skillPath,\r\n });\r\n }\r\n }\r\n }\r\n\r\n return skills;\r\n }\r\n}\r\n\r\n", "/**\r\n * HeraSpec Validate Command\r\n */\r\nimport path from 'path';\r\nimport chalk from 'chalk';\r\nimport { FileSystemUtils } from '../utils/file-system.js';\r\nimport { Validator } from '../core/validation/validator.js';\r\nimport { HERASPEC_DIR_NAME, CHANGES_DIR_NAME, SPECS_DIR_NAME } from '../core/config.js';\r\n\r\nexport class ValidateCommand {\r\n async execute(itemName?: string, options?: { strict?: boolean }): Promise<void> {\r\n const validator = new Validator(options?.strict || false);\r\n\r\n if (!itemName) {\r\n console.error('Error: Please specify a change or spec name');\r\n console.log('Usage: heraspec validate <change-name>');\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n // Try change first\r\n const changePath = path.join('.', HERASPEC_DIR_NAME, CHANGES_DIR_NAME, itemName);\r\n if (await FileSystemUtils.fileExists(changePath)) {\r\n const report = await validator.validateChange(changePath);\r\n this.printReport(itemName, report);\r\n if (!report.valid) {\r\n process.exitCode = 1;\r\n }\r\n return;\r\n }\r\n\r\n // Try spec\r\n const specPath = this.findSpecPath(itemName);\r\n if (specPath && (await FileSystemUtils.fileExists(specPath))) {\r\n const report = await validator.validateSpec(specPath);\r\n this.printReport(itemName, report);\r\n if (!report.valid) {\r\n process.exitCode = 1;\r\n }\r\n return;\r\n }\r\n\r\n console.error(`Error: Change or spec \"${itemName}\" not found`);\r\n process.exitCode = 1;\r\n }\r\n\r\n private findSpecPath(specName: string): string | null {\r\n const basePath = path.join('.', HERASPEC_DIR_NAME, SPECS_DIR_NAME);\r\n return path.join(basePath, `${specName}.md`);\r\n }\r\n\r\n private printReport(itemName: string, report: any): void {\r\n console.log(`\\nValidation Report: ${itemName}\\n`);\r\n console.log('\u2500'.repeat(60));\r\n\r\n if (report.valid) {\r\n console.log(chalk.green('\u2713 Valid'));\r\n } else {\r\n console.log(chalk.red('\u2717 Invalid'));\r\n }\r\n\r\n if (report.errors && report.errors.length > 0) {\r\n console.log(chalk.red('\\nErrors:'));\r\n report.errors.forEach((err: any) => {\r\n console.log(chalk.red(` \u2022 ${err.message || err}`));\r\n if (err.suggestion) {\r\n console.log(chalk.gray(` \uD83D\uDCA1 Suggestion: ${err.suggestion}`));\r\n }\r\n if (err.path) {\r\n console.log(chalk.gray(` \uD83D\uDCCD Path: ${err.path}`));\r\n }\r\n });\r\n }\r\n\r\n if (report.warnings && report.warnings.length > 0) {\r\n console.log(chalk.yellow('\\nWarnings:'));\r\n report.warnings.forEach((warn: any) => {\r\n console.log(chalk.yellow(` \u2022 ${warn.message || warn}`));\r\n if (warn.suggestion) {\r\n console.log(chalk.gray(` \uD83D\uDCA1 Suggestion: ${warn.suggestion}`));\r\n }\r\n if (warn.path) {\r\n console.log(chalk.gray(` \uD83D\uDCCD Path: ${warn.path}`));\r\n }\r\n });\r\n }\r\n\r\n if (report.suggestions && report.suggestions.length > 0) {\r\n console.log(chalk.cyan('\\n\uD83D\uDCA1 Quick Fixes:'));\r\n report.suggestions.forEach((suggestion: string) => {\r\n console.log(chalk.cyan(` \u2022 ${suggestion}`));\r\n });\r\n }\r\n\r\n // Provide next steps if invalid\r\n if (!report.valid && report.errors && report.errors.length > 0) {\r\n console.log(chalk.gray('\\n\uD83D\uDCDD Next Steps:'));\r\n console.log(chalk.gray(' 1. Review errors above'));\r\n console.log(chalk.gray(' 2. Apply suggested fixes'));\r\n console.log(chalk.gray(' 3. Run validation again: heraspec validate ' + itemName));\r\n }\r\n\r\n console.log('\\n' + '\u2500'.repeat(60) + '\\n');\r\n }\r\n}\r\n\r\n", "/**\r\n * HeraSpec Validator\r\n * Validates specs and changes\r\n */\r\nimport { readFileSync } from 'fs';\r\nimport path from 'path';\r\nimport { createHash } from 'crypto';\r\nimport { SpecSchema, ChangeSchema } from '../schemas/index.js';\r\nimport { MarkdownParser } from '../parsers/markdown-parser.js';\r\nimport { FileSystemUtils } from '../../utils/file-system.js';\r\nimport { HERASPEC_DIR_NAME, SPECS_DIR_NAME } from '../config.js';\r\n\r\nexport interface ValidationIssue {\r\n message: string;\r\n path?: string;\r\n line?: number;\r\n suggestion?: string;\r\n autoFixable?: boolean;\r\n}\r\n\r\nexport interface ValidationReport {\r\n valid: boolean;\r\n errors: ValidationIssue[];\r\n warnings: ValidationIssue[];\r\n suggestions?: string[];\r\n}\r\n\r\nexport class Validator {\r\n private strictMode: boolean;\r\n\r\n constructor(strictMode: boolean = false) {\r\n this.strictMode = strictMode;\r\n }\r\n\r\n async validateSpec(filePath: string): Promise<ValidationReport> {\r\n const errors: string[] = [];\r\n const warnings: string[] = [];\r\n\r\n try {\r\n const content = readFileSync(filePath, 'utf-8');\r\n const parser = new MarkdownParser(content);\r\n const specName = this.extractNameFromPath(filePath);\r\n const spec = parser.parseSpec(specName);\r\n\r\n // Validate against schema\r\n const result = SpecSchema.safeParse(spec);\r\n\r\n if (!result.success) {\r\n result.error.errors.forEach((err) => {\r\n errors.push(`${err.path.join('.')}: ${err.message}`);\r\n });\r\n }\r\n\r\n // Additional validation rules\r\n if (spec.requirements.length === 0) {\r\n errors.push('Spec must have at least one requirement');\r\n }\r\n\r\n for (const req of spec.requirements) {\r\n if (!req.description || req.description.trim().length === 0) {\r\n errors.push(`Requirement \"${req.name}\" must have a description`);\r\n }\r\n\r\n if (!req.scenarios || req.scenarios.length === 0) {\r\n warnings.push(`Requirement \"${req.name}\" has no scenarios`);\r\n }\r\n }\r\n\r\n return {\r\n valid: errors.length === 0,\r\n errors,\r\n warnings,\r\n };\r\n } catch (error) {\r\n return {\r\n valid: false,\r\n errors: [error instanceof Error ? error.message : 'Unknown error'],\r\n warnings: [],\r\n };\r\n }\r\n }\r\n\r\n async validateChange(changePath: string): Promise<ValidationReport> {\r\n const errors: ValidationIssue[] = [];\r\n const warnings: ValidationIssue[] = [];\r\n const suggestions: string[] = [];\r\n\r\n // Check for proposal.md\r\n const proposalPath = path.join(changePath, 'proposal.md');\r\n if (!(await FileSystemUtils.fileExists(proposalPath))) {\r\n errors.push({\r\n message: 'Change must have a proposal.md file',\r\n path: proposalPath,\r\n suggestion: `Create proposal.md in ${changePath} with: # Change Proposal: [name]\\n\\n## Purpose\\n[Description]\\n\\n## Scope\\n[What will change]`,\r\n autoFixable: false,\r\n });\r\n suggestions.push(`Create proposal.md file at ${proposalPath}`);\r\n }\r\n\r\n // Check for tasks.md\r\n const tasksPath = path.join(changePath, 'tasks.md');\r\n if (!(await FileSystemUtils.fileExists(tasksPath))) {\r\n warnings.push({\r\n message: 'Change has no tasks.md file',\r\n path: tasksPath,\r\n suggestion: `Create tasks.md with implementation tasks grouped by project type and skill`,\r\n autoFixable: false,\r\n });\r\n }\r\n\r\n // Validate delta specs if they exist\r\n // Specs are now in heraspec/specs/<changeName>/ instead of heraspec/changes/<changeName>/specs/\r\n const changeName = path.basename(changePath);\r\n const specsDir = path.join(\r\n '.',\r\n HERASPEC_DIR_NAME,\r\n SPECS_DIR_NAME,\r\n changeName\r\n );\r\n if (await FileSystemUtils.fileExists(specsDir)) {\r\n const deltaSpecs = await this.findDeltaSpecs(specsDir);\r\n for (const specPath of deltaSpecs) {\r\n const report = await this.validateDeltaSpec(specPath, changePath);\r\n errors.push(...report.errors);\r\n warnings.push(...report.warnings);\r\n if (report.suggestions) {\r\n suggestions.push(...report.suggestions);\r\n }\r\n }\r\n } else {\r\n warnings.push({\r\n message: 'No delta specs found for this change',\r\n suggestion: `Create delta specs in ${specsDir}/spec.md using ADDED/MODIFIED/REMOVED sections`,\r\n autoFixable: false,\r\n });\r\n }\r\n\r\n return {\r\n valid: errors.length === 0,\r\n errors,\r\n warnings,\r\n suggestions: suggestions.length > 0 ? suggestions : undefined,\r\n };\r\n }\r\n\r\n private async validateDeltaSpec(filePath: string, changePath?: string): Promise<ValidationReport> {\r\n const errors: ValidationIssue[] = [];\r\n const warnings: ValidationIssue[] = [];\r\n const suggestions: string[] = [];\r\n\r\n try {\r\n const content = readFileSync(filePath, 'utf-8');\r\n const parser = new MarkdownParser(content);\r\n const delta = parser.parseDeltaSpec(content);\r\n\r\n // Auto-capture base fingerprints for Modified/Removed requirements\r\n if (changePath && (delta.modified.length > 0 || delta.removed.length > 0)) {\r\n await this.captureFingerprints(changePath, filePath, delta);\r\n }\r\n\r\n // Check that delta has at least one section\r\n if (delta.added.length === 0 && delta.modified.length === 0 && delta.removed.length === 0) {\r\n warnings.push({\r\n message: 'Delta spec has no changes',\r\n suggestion: 'Add at least one section: ## ADDED Requirements, ## MODIFIED Requirements, or ## REMOVED Requirements',\r\n autoFixable: false,\r\n });\r\n }\r\n\r\n // Check for proper delta format\r\n if (!content.includes('## ADDED') && !content.includes('## MODIFIED') && !content.includes('## REMOVED')) {\r\n warnings.push({\r\n message: 'Delta spec may not follow proper format',\r\n suggestion: 'Use sections: ## ADDED Requirements, ## MODIFIED Requirements, ## REMOVED Requirements',\r\n autoFixable: false,\r\n });\r\n }\r\n\r\n return {\r\n valid: errors.length === 0,\r\n errors,\r\n warnings,\r\n suggestions: suggestions.length > 0 ? suggestions : undefined,\r\n };\r\n } catch (error) {\r\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\r\n const suggestion = this.getParseErrorSuggestion(errorMessage);\r\n \r\n return {\r\n valid: false,\r\n errors: [{\r\n message: errorMessage,\r\n suggestion,\r\n autoFixable: false,\r\n }],\r\n warnings: [],\r\n suggestions: suggestion ? [suggestion] : undefined,\r\n };\r\n }\r\n }\r\n\r\n private extractNameFromPath(filePath: string): string {\r\n const baseName = path.basename(filePath, '.md');\r\n return baseName === 'spec' ? path.basename(path.dirname(filePath)) : baseName;\r\n }\r\n\r\n private async findDeltaSpecs(dir: string): Promise<string[]> {\r\n const specs: string[] = [];\r\n const entries = await FileSystemUtils.readDirectory(dir);\r\n\r\n for (const entry of entries) {\r\n const entryPath = path.join(dir, entry);\r\n const stats = await FileSystemUtils.stat(entryPath);\r\n\r\n if (stats.isDirectory()) {\r\n const subSpecs = await this.findDeltaSpecs(entryPath);\r\n specs.push(...subSpecs);\r\n } else if (entry.endsWith('.md')) {\r\n specs.push(entryPath);\r\n }\r\n }\r\n\r\n return specs;\r\n }\r\n\r\n private async captureFingerprints(changePath: string, deltaSpecPath: string, delta: any): Promise<void> {\r\n const changeName = path.basename(changePath);\r\n // Find corresponding source spec path\r\n const specsDir = path.join(HERASPEC_DIR_NAME, SPECS_DIR_NAME);\r\n const deltaSpecsDir = path.join(specsDir, changeName);\r\n \r\n // Using string replacement to resolve relative paths might be tricky with path separators. \r\n // A safer way:\r\n const relativePath = path.relative(path.resolve(deltaSpecsDir), path.resolve(deltaSpecPath));\r\n const sourceSpecPath = path.join(path.resolve(specsDir), relativePath);\r\n\r\n let sourceContent = '';\r\n if (await FileSystemUtils.fileExists(sourceSpecPath)) {\r\n sourceContent = readFileSync(sourceSpecPath, 'utf-8');\r\n }\r\n\r\n const fingerprintsPath = path.join(changePath, 'fingerprints.json');\r\n let fingerprints: Record<string, string> = {};\r\n if (await FileSystemUtils.fileExists(fingerprintsPath)) {\r\n fingerprints = JSON.parse(readFileSync(fingerprintsPath, 'utf-8'));\r\n }\r\n\r\n let updated = false;\r\n const reqs = [...delta.modified, ...delta.removed];\r\n \r\n for (const req of reqs) {\r\n const hashKey = `${relativePath}:${req.name}`;\r\n if (!fingerprints[hashKey]) {\r\n const reqBlock = this.extractRequirementBlock(sourceContent, req.name);\r\n if (reqBlock) {\r\n fingerprints[hashKey] = createHash('sha256').update(reqBlock).digest('hex');\r\n updated = true;\r\n }\r\n }\r\n }\r\n\r\n if (updated) {\r\n await FileSystemUtils.writeFile(fingerprintsPath, JSON.stringify(fingerprints, null, 2));\r\n }\r\n }\r\n\r\n private extractRequirementBlock(content: string, reqName: string): string | null {\r\n const escapedName = reqName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n const reqRegex = new RegExp(`###\\\\s+Requirement:\\\\s*${escapedName}\\\\s*\\\\n([\\\\s\\\\S]*?)(?=(?:###\\\\s+Requirement:|$))`, 'i');\r\n const match = content.match(reqRegex);\r\n return match ? match[0].trim() : null;\r\n }\r\n}\r\n\r\n", "/**\r\n * Base schemas for HeraSpec\r\n */\r\nimport { z } from 'zod';\r\n\r\nexport const ProjectTypeSchema = z.enum([\r\n 'wordpress-plugin',\r\n 'wordpress-theme',\r\n 'perfex-module',\r\n 'laravel-package',\r\n 'node-service',\r\n 'generic-webapp',\r\n 'backend-api',\r\n 'frontend-app',\r\n 'multi-stack',\r\n]);\r\n\r\nexport const SpecMetaSchema = z.object({\r\n projectType: z.union([\r\n ProjectTypeSchema,\r\n z.array(ProjectTypeSchema),\r\n ]).optional(),\r\n domain: z.string().optional(),\r\n stack: z.union([\r\n z.string(),\r\n z.array(z.string()),\r\n ]).optional(),\r\n}).optional();\r\n\r\nexport const ScenarioSchema = z.object({\r\n name: z.string(),\r\n steps: z.array(z.string()).min(1),\r\n});\r\n\r\nexport const RequirementSchema = z.object({\r\n id: z.string().optional(),\r\n name: z.string(),\r\n description: z.string(),\r\n scenarios: z.array(ScenarioSchema).optional(),\r\n constraints: z.array(z.string()).optional(),\r\n});\r\n\r\n", "/**\r\n * HeraSpec Specification Schema\r\n */\r\nimport { z } from 'zod';\r\nimport { RequirementSchema, SpecMetaSchema } from './base.schema.js';\r\n\r\nexport const SpecSchema = z.object({\r\n name: z.string().min(1),\r\n meta: SpecMetaSchema,\r\n overview: z.string().min(1),\r\n requirements: z.array(RequirementSchema).min(1),\r\n metadata: z.object({\r\n version: z.string().default('1.0.0'),\r\n format: z.literal('heraspec'),\r\n sourcePath: z.string().optional(),\r\n }).optional(),\r\n});\r\n\r\nexport type Spec = z.infer<typeof SpecSchema>;\r\n\r\n", "/**\r\n * HeraSpec Change Schema\r\n */\r\nimport { z } from 'zod';\r\n\r\nexport const DeltaTypeSchema = z.enum(['ADDED', 'MODIFIED', 'REMOVED']);\r\n\r\nexport const DeltaRequirementSchema = z.object({\r\n type: DeltaTypeSchema,\r\n requirement: z.object({\r\n id: z.string().optional(),\r\n name: z.string(),\r\n description: z.string(),\r\n scenarios: z.array(z.object({\r\n name: z.string(),\r\n steps: z.array(z.string()),\r\n })).optional(),\r\n constraints: z.array(z.string()).optional(),\r\n }),\r\n});\r\n\r\nexport const ChangeSchema = z.object({\r\n name: z.string(),\r\n proposal: z.string().min(1),\r\n tasks: z.array(z.string()).optional(),\r\n design: z.string().optional(),\r\n});\r\n\r\nexport type Change = z.infer<typeof ChangeSchema>;\r\nexport type DeltaRequirement = z.infer<typeof DeltaRequirementSchema>;\r\n\r\n", "/**\r\n * HeraSpec Helper Command\r\n * Displays usage guides, example prompts, and workflow instructions\r\n */\r\n\r\nimport chalk from 'chalk';\r\n\r\nexport class HelperCommand {\r\n async execute(): Promise<void> {\r\n console.log(chalk.cyan.bold('\\n\uD83D\uDCDA HeraSpec Helper - Usage Guide\\n'));\r\n console.log('\u2550'.repeat(70) + '\\n');\r\n\r\n this.showQuickStart();\r\n this.showCommands();\r\n this.showExamplePrompts();\r\n this.showWorkflow();\r\n this.showTips();\r\n\r\n console.log('\\n' + '\u2550'.repeat(70));\r\n console.log(chalk.gray('\\n\uD83D\uDCA1 Tip: See details at docs/README.md (available in multiple languages)\\n'));\r\n }\r\n\r\n private showQuickStart(): void {\r\n console.log(chalk.yellow.bold('\uD83D\uDE80 Quick Start\\n'));\r\n console.log(chalk.white('1. Initialize a new project:'));\r\n console.log(chalk.gray(' cd my-project'));\r\n console.log(chalk.cyan(' heraspec init\\n'));\r\n\r\n console.log(chalk.white('2. Configure project.md:'));\r\n console.log(chalk.gray(' Edit heraspec/project.md with your project information\\n'));\r\n\r\n console.log(chalk.white('3. Create your first change (using AI):'));\r\n console.log(chalk.cyan(' \"Create a HeraSpec change to add feature X\"\\n'));\r\n\r\n console.log(chalk.white('4. View list:'));\r\n console.log(chalk.cyan(' heraspec list\\n'));\r\n\r\n console.log('\u2500'.repeat(70) + '\\n');\r\n }\r\n\r\n private showCommands(): void {\r\n console.log(chalk.yellow.bold('\u26A1 Main CLI Commands\\n'));\r\n \r\n const commands = [\r\n { cmd: 'heraspec init [path]', desc: 'Initialize HeraSpec in project' },\r\n { cmd: 'heraspec list', desc: 'List changes (default)' },\r\n { cmd: 'heraspec list --specs', desc: 'List specs' },\r\n { cmd: 'heraspec skills', desc: 'List all available skills (shortcut)' },\r\n { cmd: 'heraspec show [name]', desc: 'Show change or spec details' },\r\n { cmd: 'heraspec validate [name]', desc: 'Validate change or spec' },\r\n { cmd: 'heraspec archive [name]', desc: 'Archive completed change' },\r\n { cmd: 'heraspec restore [name]', desc: 'Restore change from archive' },\r\n { cmd: 'heraspec skill list', desc: 'List available skills' },\r\n { cmd: 'heraspec skill show <name>', desc: 'Show skill details' },\r\n { cmd: 'heraspec make docs', desc: 'Generate product documentation' },\r\n { cmd: 'heraspec make docs --agent <name>', desc: 'Generate docs with AI agent' },\r\n { cmd: 'heraspec make test', desc: 'Generate test cases from specs' },\r\n { cmd: 'heraspec make test --type <type>', desc: 'Generate tests (unit/integration/e2e)' },\r\n { cmd: 'heraspec suggest', desc: 'Suggest new features for project' },\r\n { cmd: 'heraspec view', desc: 'View dashboard overview' },\r\n { cmd: 'heraspec helper', desc: 'Show this guide' },\r\n ];\r\n\r\n commands.forEach(({ cmd, desc }) => {\r\n console.log(chalk.cyan(` ${cmd.padEnd(35)}`) + chalk.white(desc));\r\n });\r\n\r\n console.log('\\n' + '\u2500'.repeat(70) + '\\n');\r\n }\r\n\r\n private showExamplePrompts(): void {\r\n console.log(chalk.yellow.bold('\uD83D\uDCAC Example Prompts for AI\\n'));\r\n\r\n console.log(chalk.white.bold('1. Simple Change Creation:\\n'));\r\n console.log(chalk.gray(' \"Create a HeraSpec change to add 2FA authentication feature\"\\n'));\r\n console.log(chalk.gray(' \"Create HeraSpec change for order management module\"\\n'));\r\n\r\n console.log(chalk.white.bold('2. Create Change Based on project.md:\\n'));\r\n console.log(chalk.gray(' \"Read heraspec/project.md and create HeraSpec changes for all\\n'));\r\n console.log(chalk.gray(' features mentioned in it\"\\n'));\r\n console.log(chalk.gray(' \"Based on project.md, create changes to implement by phase\"\\n'));\r\n\r\n console.log(chalk.white.bold('3. Detailed Change Creation:\\n'));\r\n console.log(chalk.gray(' \"Create HeraSpec change with the following steps:\\n'));\r\n console.log(chalk.gray(' 1. Read and analyze heraspec/project.md\\n'));\r\n console.log(chalk.gray(' 2. Identify features to build\\n'));\r\n console.log(chalk.gray(' 3. For each feature, create a separate change\\n'));\r\n console.log(chalk.gray(' 4. Each change needs proposal.md, tasks.md, specs/\\n'));\r\n console.log(chalk.gray(' 5. Follow conventions in project.md\"\\n'));\r\n\r\n console.log(chalk.white.bold('4. Prompt With Project Type and Skill:\\n'));\r\n console.log(chalk.gray(' \"Create change for WordPress plugin with skill admin-settings-page\"\\n'));\r\n console.log(chalk.gray(' \"Create change for Perfex module with skill module-codebase\"\\n'));\r\n console.log(chalk.gray(' \"Create UI/UX change with skill ui-ux for admin interface\"\\n'));\r\n\r\n console.log(chalk.white.bold('5. View and Validate:\\n'));\r\n console.log(chalk.gray(' \"View change add-user-auth\"\\n'));\r\n console.log(chalk.gray(' \"Validate change add-user-auth --strict\"\\n'));\r\n console.log(chalk.gray(' \"List all changes\"\\n'));\r\n\r\n console.log(chalk.white.bold('6. Implementation:\\n'));\r\n console.log(chalk.gray(' \"Specs approved, start implementing change add-user-auth\"\\n'));\r\n console.log(chalk.gray(' \"Execute tasks in change add-user-auth\"\\n'));\r\n\r\n console.log(chalk.white.bold('7. Generate Documentation:\\n'));\r\n console.log(chalk.gray(' \"Generate product documentation from specs\"\\n'));\r\n console.log(chalk.gray(' heraspec make docs\\n'));\r\n console.log(chalk.gray(' \"Generate docs with specific AI agent\"\\n'));\r\n console.log(chalk.gray(' heraspec make docs --agent chatgpt\\n'));\r\n console.log(chalk.gray(' heraspec make docs --agent claude\\n'));\r\n \r\n console.log(chalk.white.bold('8. Multi-Format Documentation (Skill: Documents):\\n'));\r\n console.log(chalk.gray(' \"Generate documentation with skill documents for [project-name]. Include:\\n'));\r\n console.log(chalk.gray(' - Concise overview (documentation.txt)\\n'));\r\n console.log(chalk.gray(' - Technical Markdown (documentation.md)\\n'));\r\n console.log(chalk.gray(' - Interactive HTML Documentation (documentation.html)\\n'));\r\n console.log(chalk.gray(' - Premium Documentation Landing Page (documentation-landing-page.html)\"\\n'));\r\n console.log(chalk.gray(' \"Use documents skill to create dynamic, project-specific docs\"\\n'));\r\n\r\n console.log(chalk.gray(' \"Use test skills: unit-test, integration-test, e2e-test for test implementation\"'));\r\n\r\n console.log(chalk.white.bold('9. WordPress Plugin Check:\\n'));\r\n console.log(chalk.gray(' \"Use skill plugin-check to check, then resolve *all* issues mentioned for plugin `[TARGET_PLUGIN]`\"\\n'));\r\n console.log(chalk.gray(' \"Ensure careful handling and verify that related features still function correctly.\"\\n'));\r\n\r\n console.log('\u2500'.repeat(70) + '\\n');\r\n }\r\n\r\n private showWorkflow(): void {\r\n console.log(chalk.yellow.bold('\uD83D\uDD04 Workflow\\n'));\r\n\r\n const steps = [\r\n {\r\n step: '1. Create Change',\r\n actions: [\r\n 'AI or you create change directory',\r\n 'Write proposal.md describing purpose',\r\n 'Create tasks.md with task list',\r\n 'Write delta specs in specs/',\r\n ],\r\n prompt: '\"Create HeraSpec change to...\"',\r\n },\r\n {\r\n step: '2. Refine Specs',\r\n actions: [\r\n 'Review: heraspec show <name>',\r\n 'Ask AI to edit if needed',\r\n 'Validate: heraspec validate <name>',\r\n ],\r\n prompt: '\"Edit specs in change...\"',\r\n },\r\n {\r\n step: '3. Approval',\r\n actions: ['Wait for user: \"Specs approved.\"'],\r\n prompt: 'You confirm: \"Specs approved.\"',\r\n },\r\n {\r\n step: '4. Implementation',\r\n actions: [\r\n 'AI reads tasks.md and skill.md',\r\n 'Execute each task',\r\n 'Mark completed: - [x]',\r\n ],\r\n prompt: '\"Specs approved, implement change...\"',\r\n },\r\n {\r\n step: '5. Archive',\r\n actions: [\r\n 'Review: heraspec show <name>',\r\n 'Archive: heraspec archive <name> --yes',\r\n 'Specs merged into source specs',\r\n ],\r\n prompt: 'heraspec archive <name> --yes',\r\n },\r\n {\r\n step: '6. Generate Documentation',\r\n actions: [\r\n 'Generate basic docs: heraspec make docs',\r\n 'Use Skill Documents: \"Generate documentation with skill documents\"',\r\n 'Outputs: documentation.txt, .md, .html, and landing-page.html',\r\n 'Agent uses ui-ux skill for premium dynamic design',\r\n ],\r\n prompt: '\"Generate documentation with skill documents for [project-name]\"',\r\n },\r\n {\r\n step: '7. Quality Check (Plugin Check)',\r\n actions: [\r\n 'Run Plugin Check: \"Use skill plugin-check...\"',\r\n 'Agent iterates until all issues resolved',\r\n 'Safety check: Verify features functionality',\r\n ],\r\n prompt: '\"Use skill plugin-check to check plugin [target-plugin]\"',\r\n },\r\n ];\r\n\r\n steps.forEach(({ step, actions, prompt }) => {\r\n console.log(chalk.cyan.bold(` ${step}`));\r\n actions.forEach((action) => {\r\n console.log(chalk.white(` \u2022 ${action}`));\r\n });\r\n console.log(chalk.gray(` \uD83D\uDCAC ${prompt}\\n`));\r\n });\r\n\r\n console.log('\u2500'.repeat(70) + '\\n');\r\n }\r\n\r\n private showTips(): void {\r\n console.log(chalk.yellow.bold('\uD83D\uDCA1 Tips & Best Practices\\n'));\r\n\r\n const tips = [\r\n 'Always read heraspec/project.md before creating change',\r\n 'Use Skills system when implementing (each task has skill tag)',\r\n 'Validate specs before requesting approval',\r\n 'One change should focus on one specific feature',\r\n 'Name change: kebab-case, verb-led (add-, create-, implement-)',\r\n 'Delta specs only change in change folder',\r\n 'Do not edit source-of-truth specs directly',\r\n 'Archive change after completion to merge specs',\r\n 'Use heraspec skill list to view available skills',\r\n 'UI/UX tasks: Use search scripts in skill ui-ux',\r\n 'Premium Documentation: Use \"skill documents\" for txt, md, html, and landing page',\r\n 'Dynamic Docs: Documents skill generates custom layouts based on your project specs',\r\n 'Generate product docs: heraspec make docs (default agent: chatgpt)',\r\n 'Specify AI agent: heraspec make docs --agent <name> (chatgpt, claude, etc.)',\r\n 'Generate tests: heraspec make test (default: unit)',\r\n 'Test types: unit (individual functions), integration (components), e2e (user flows)',\r\n 'Generate code: heraspec make code (generates code skeletons from specs)',\r\n 'Validate with suggestions: heraspec validate <name> (includes fix suggestions)',\r\n 'Get feature suggestions: heraspec suggest (analyzes project and suggests enhancements)',\r\n 'Use test skills: unit-test, integration-test, e2e-test for test implementation',\r\n 'Plugin Check: Use \"skill plugin-check\" to ensure code quality and safety',\r\n ];\r\n\r\n tips.forEach((tip) => {\r\n console.log(chalk.white(` \u2022 ${tip}`));\r\n });\r\n\r\n console.log('');\r\n }\r\n}\r\n", "/**\r\n * HeraSpec Make Docs Command\r\n * Generates user-friendly product documentation from specs\r\n */\r\nimport path from 'path';\r\nimport chalk from 'chalk';\r\nimport ora from 'ora';\r\nimport { FileSystemUtils } from '../utils/file-system.js';\r\nimport { HERASPEC_DIR_NAME, SPECS_DIR_NAME, HERASPEC_MARKERS } from '../core/config.js';\r\n\r\nexport class MakeDocsCommand {\r\n async execute(projectPath: string = '.', agent: string = 'chatgpt'): Promise<void> {\r\n const spinner = ora(`Generating product documentation (Agent: ${agent})...`).start();\r\n\r\n try {\r\n const resolvedPath = path.resolve(projectPath);\r\n const specsDir = path.join(resolvedPath, HERASPEC_DIR_NAME, SPECS_DIR_NAME);\r\n const docsDir = path.join(resolvedPath, 'documentations');\r\n const projectMdPath = path.join(resolvedPath, HERASPEC_DIR_NAME, HERASPEC_MARKERS.PROJECT_MD);\r\n\r\n // Check if specs directory exists\r\n if (!(await FileSystemUtils.fileExists(specsDir))) {\r\n spinner.fail('Specs directory not found. Run \"heraspec init\" first.');\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n // Ensure documentation directory exists\r\n await FileSystemUtils.createDirectory(docsDir);\r\n\r\n // Read project.md if exists (for context)\r\n let projectInfo: { name?: string; description?: string } = {};\r\n if (await FileSystemUtils.fileExists(projectMdPath)) {\r\n const projectContent = await FileSystemUtils.readFile(projectMdPath);\r\n projectInfo = this.extractProjectInfo(projectContent);\r\n }\r\n\r\n // Check for Skills\r\n const hasDocumentsSkill = await FileSystemUtils.fileExists(path.join(resolvedPath, HERASPEC_DIR_NAME, 'skills', 'documents'));\r\n const hasUIUXSkill = await FileSystemUtils.fileExists(path.join(resolvedPath, HERASPEC_DIR_NAME, 'skills', 'ui-ux'));\r\n\r\n // Find all spec files\r\n const specFiles = await this.findSpecFiles(specsDir);\r\n\r\n if (specFiles.length === 0) {\r\n spinner.warn('No specs found. Create specs first using \"heraspec list --specs\".');\r\n return;\r\n }\r\n\r\n // Read and parse all specs\r\n const specs = await this.readSpecs(specFiles);\r\n\r\n // Generate user-friendly documentation\r\n const docContent = this.generateProductDocumentation(specs, projectInfo, agent);\r\n\r\n // Write documentation file\r\n const docFilePath = path.join(docsDir, 'documentation.txt');\r\n await FileSystemUtils.writeFile(docFilePath, docContent);\r\n\r\n spinner.succeed(`Basic documentation generated: ${docFilePath}`);\r\n\r\n if (hasDocumentsSkill) {\r\n console.log(chalk.green.bold('\\n\u2728 Documents Skill Detected!'));\r\n console.log(chalk.white('AI Agent Instruction:'));\r\n console.log(chalk.gray(' \"Now use the documents skill to generate the full multi-format package:'));\r\n console.log(chalk.gray(' - Use documentation.txt as context'));\r\n console.log(chalk.gray(' - Create documentation.md, documentation.html, and landing page'));\r\n console.log(chalk.gray(' - CRITICAL: Save all files in the /documentations directory (create it if missing)'));\r\n if (hasUIUXSkill) {\r\n console.log(chalk.gray(' - Apply premium design from the ui-ux skill standards\"'));\r\n } else {\r\n console.log(chalk.yellow(' - WARNING: \"ui-ux\" skill is MISSING but required for HTML/Landing Page.'));\r\n console.log(chalk.gray(' - Agent must install it first: heraspec skill add ui-ux\"'));\r\n }\r\n } else {\r\n console.log(chalk.yellow('\\n\uD83D\uDCA1 Tip: Add the \"documents\" skill for premium HTML & Landing Page support:'));\r\n console.log(chalk.gray(' heraspec skill add documents'));\r\n }\r\n\r\n console.log(chalk.gray(`\\nFound ${specFiles.length} feature(s)`));\r\n } catch (error) {\r\n spinner.fail(`Error: ${(error as Error).message}`);\r\n process.exitCode = 1;\r\n throw error;\r\n }\r\n }\r\n\r\n /**\r\n * Extract project information from project.md\r\n */\r\n private extractProjectInfo(projectContent: string): { name?: string; description?: string } {\r\n const info: { name?: string; description?: string } = {};\r\n \r\n // Extract project name (usually first heading or after # Project Name)\r\n const nameMatch = projectContent.match(/^#\\s+(.+)$/m);\r\n if (nameMatch) {\r\n info.name = nameMatch[1].trim();\r\n }\r\n\r\n // Extract description (first paragraph after title)\r\n const lines = projectContent.split('\\n');\r\n let descriptionStart = false;\r\n const descriptionLines: string[] = [];\r\n \r\n for (const line of lines) {\r\n if (line.startsWith('#') && !descriptionStart) {\r\n descriptionStart = true;\r\n continue;\r\n }\r\n if (descriptionStart && line.trim() && !line.startsWith('#')) {\r\n descriptionLines.push(line.trim());\r\n if (descriptionLines.length >= 3) break; // Get first few lines\r\n }\r\n }\r\n \r\n if (descriptionLines.length > 0) {\r\n info.description = descriptionLines.join(' ');\r\n }\r\n\r\n return info;\r\n }\r\n\r\n /**\r\n * Find all spec files recursively\r\n */\r\n private async findSpecFiles(specsDir: string): Promise<string[]> {\r\n const specFiles: string[] = [];\r\n await this.findSpecFilesRecursive(specsDir, specFiles);\r\n return specFiles.sort();\r\n }\r\n\r\n /**\r\n * Recursively find spec files\r\n */\r\n private async findSpecFilesRecursive(dir: string, files: string[]): Promise<void> {\r\n const fs = await import('fs/promises');\r\n const entries = await fs.readdir(dir, { withFileTypes: true });\r\n\r\n for (const entry of entries) {\r\n const entryPath = path.join(dir, entry.name);\r\n\r\n if (entry.isDirectory()) {\r\n await this.findSpecFilesRecursive(entryPath, files);\r\n } else if (entry.name.endsWith('.md')) {\r\n files.push(entryPath);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Read all spec files\r\n */\r\n private async readSpecs(specFiles: string[]): Promise<Array<{ path: string; content: string; name: string }>> {\r\n const specs = [];\r\n\r\n for (const specFile of specFiles) {\r\n const content = await FileSystemUtils.readFile(specFile);\r\n const name = this.extractFeatureName(specFile, content);\r\n\r\n specs.push({\r\n path: specFile,\r\n content,\r\n name,\r\n });\r\n }\r\n\r\n return specs;\r\n }\r\n\r\n /**\r\n * Extract feature name from spec file\r\n */\r\n private extractFeatureName(filePath: string, content: string): string {\r\n // Try to get from first heading\r\n const headingMatch = content.match(/^#+\\s+(.+)$/m);\r\n if (headingMatch) {\r\n return headingMatch[1].trim();\r\n }\r\n \r\n // Fallback to filename\r\n return path.basename(filePath, '.md')\r\n .split('-')\r\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\r\n .join(' ');\r\n }\r\n\r\n /**\r\n * Generate product documentation from specs\r\n */\r\n private generateProductDocumentation(\r\n specs: Array<{ path: string; content: string; name: string }>,\r\n projectInfo: { name?: string; description?: string },\r\n agent: string = 'chatgpt'\r\n ): string {\r\n const lines: string[] = [];\r\n\r\n // Title\r\n const productName = projectInfo.name || 'Product';\r\n lines.push(`# ${productName}`);\r\n lines.push('');\r\n\r\n // Description\r\n if (projectInfo.description) {\r\n lines.push(projectInfo.description);\r\n lines.push('');\r\n }\r\n\r\n lines.push('---');\r\n lines.push('');\r\n\r\n // Overview\r\n lines.push('## Overview');\r\n lines.push('');\r\n lines.push(`This product includes ${specs.length} main feature${specs.length > 1 ? 's' : ''}:`);\r\n lines.push('');\r\n specs.forEach((spec, index) => {\r\n lines.push(`${index + 1}. ${spec.name}`);\r\n });\r\n lines.push('');\r\n lines.push('---');\r\n lines.push('');\r\n\r\n // Features (user-friendly descriptions)\r\n lines.push('## Features');\r\n lines.push('');\r\n\r\n specs.forEach((spec, index) => {\r\n const featureInfo = this.extractFeatureInfo(spec.content);\r\n \r\n lines.push(`### ${index + 1}. ${spec.name}`);\r\n lines.push('');\r\n\r\n // Purpose/Description\r\n if (featureInfo.description) {\r\n lines.push(featureInfo.description);\r\n lines.push('');\r\n }\r\n\r\n // Key Capabilities\r\n if (featureInfo.capabilities.length > 0) {\r\n lines.push('**Key Capabilities:**');\r\n lines.push('');\r\n featureInfo.capabilities.forEach(cap => {\r\n lines.push(`- ${cap}`);\r\n });\r\n lines.push('');\r\n }\r\n\r\n // Use Cases (if any scenarios)\r\n if (featureInfo.useCases.length > 0) {\r\n lines.push('**Use Cases:**');\r\n lines.push('');\r\n featureInfo.useCases.forEach(useCase => {\r\n lines.push(`- ${useCase}`);\r\n });\r\n lines.push('');\r\n }\r\n\r\n if (index < specs.length - 1) {\r\n lines.push('---');\r\n lines.push('');\r\n }\r\n });\r\n\r\n // Footer\r\n lines.push('');\r\n lines.push('---');\r\n lines.push('');\r\n lines.push(`*This documentation is auto-generated from product specifications using ${agent}.*`);\r\n lines.push('');\r\n\r\n return lines.join('\\n');\r\n }\r\n\r\n /**\r\n * Extract user-friendly information from spec content\r\n */\r\n private extractFeatureInfo(content: string): {\r\n description: string;\r\n capabilities: string[];\r\n useCases: string[];\r\n } {\r\n const info: { description: string; capabilities: string[]; useCases: string[] } = {\r\n description: '',\r\n capabilities: [],\r\n useCases: [],\r\n };\r\n\r\n const lines = content.split('\\n');\r\n let inPurpose = false;\r\n let inRequirements = false;\r\n let inScenarios = false;\r\n let currentSection = '';\r\n\r\n for (let i = 0; i < lines.length; i++) {\r\n const line = lines[i];\r\n const trimmed = line.trim();\r\n\r\n // Detect sections\r\n if (trimmed.match(/^##+\\s+Purpose/i)) {\r\n inPurpose = true;\r\n inRequirements = false;\r\n inScenarios = false;\r\n continue;\r\n } else if (trimmed.match(/^##+\\s+Requirements?/i)) {\r\n inPurpose = false;\r\n inRequirements = true;\r\n inScenarios = false;\r\n continue;\r\n } else if (trimmed.match(/^##+\\s+Scenarios?/i)) {\r\n inPurpose = false;\r\n inRequirements = false;\r\n inScenarios = true;\r\n continue;\r\n } else if (trimmed.match(/^##+/)) {\r\n // New section, stop current\r\n inPurpose = false;\r\n inRequirements = false;\r\n inScenarios = false;\r\n continue;\r\n }\r\n\r\n // Extract Purpose as description\r\n if (inPurpose && trimmed && !trimmed.startsWith('#')) {\r\n if (!info.description) {\r\n info.description = trimmed;\r\n } else if (info.description.length < 300) {\r\n info.description += ' ' + trimmed;\r\n }\r\n }\r\n\r\n // Extract Requirements as capabilities\r\n if (inRequirements && trimmed.startsWith('-')) {\r\n const requirement = trimmed.replace(/^-\\s*/, '').trim();\r\n if (requirement) {\r\n // Clean up technical terms, make user-friendly\r\n const userFriendly = this.makeUserFriendly(requirement);\r\n info.capabilities.push(userFriendly);\r\n }\r\n }\r\n\r\n // Extract Scenarios as use cases\r\n if (inScenarios && trimmed.match(/^[*-]\\s*.+:/)) {\r\n const scenario = trimmed.replace(/^[*-]\\s*/, '').split(':')[0].trim();\r\n if (scenario) {\r\n const userFriendly = this.makeUserFriendly(scenario);\r\n info.useCases.push(userFriendly);\r\n }\r\n }\r\n }\r\n\r\n // If no description found, use first paragraph\r\n if (!info.description) {\r\n for (const line of lines) {\r\n const trimmed = line.trim();\r\n if (trimmed && !trimmed.startsWith('#') && trimmed.length > 20) {\r\n info.description = trimmed;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n return info;\r\n }\r\n\r\n /**\r\n * Make technical text more user-friendly\r\n */\r\n private makeUserFriendly(text: string): string {\r\n // Remove technical markers\r\n let result = text\r\n .replace(/\\([^)]*\\)/g, '') // Remove parentheses\r\n .replace(/\\[([^\\]]+)\\]/g, '$1') // Convert [text] to text\r\n .replace(/\\{([^}]+)\\}/g, '$1') // Convert {text} to text\r\n .replace(/\\b(GET|POST|PUT|DELETE|API|REST|HTTP)\\b/gi, '') // Remove API terms\r\n .replace(/\\b(endpoint|route|method|parameter|query|body)\\b/gi, '') // Remove technical terms\r\n .trim();\r\n\r\n // Capitalize first letter\r\n if (result) {\r\n result = result.charAt(0).toUpperCase() + result.slice(1);\r\n }\r\n\r\n // Clean up multiple spaces\r\n result = result.replace(/\\s+/g, ' ');\r\n\r\n return result;\r\n }\r\n}\r\n", "/**\r\n * HeraSpec Make Test Command\r\n * Generates test cases for project features\r\n */\r\nimport path from 'path';\r\nimport chalk from 'chalk';\r\nimport ora from 'ora';\r\nimport { FileSystemUtils } from '../utils/file-system.js';\r\nimport { HERASPEC_DIR_NAME, SPECS_DIR_NAME, HERASPEC_MARKERS } from '../core/config.js';\r\n\r\nexport class MakeTestCommand {\r\n async execute(projectPath: string = '.', testType: string = 'unit'): Promise<void> {\r\n const spinner = ora(`Generating ${testType} tests...`).start();\r\n\r\n try {\r\n const resolvedPath = path.resolve(projectPath);\r\n const specsDir = path.join(resolvedPath, HERASPEC_DIR_NAME, SPECS_DIR_NAME);\r\n const projectMdPath = path.join(resolvedPath, HERASPEC_DIR_NAME, HERASPEC_MARKERS.PROJECT_MD);\r\n\r\n // Check if specs directory exists\r\n if (!(await FileSystemUtils.fileExists(specsDir))) {\r\n spinner.fail('Specs directory not found. Run \"heraspec init\" first.');\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n // Determine test directory based on project type (can be customized)\r\n const testDir = this.getTestDirectory(resolvedPath, testType);\r\n\r\n // Ensure test directory exists\r\n await FileSystemUtils.createDirectory(testDir);\r\n\r\n // Read project.md if exists\r\n let projectInfo: { projectType?: string; stack?: string[] } = {};\r\n if (await FileSystemUtils.fileExists(projectMdPath)) {\r\n const projectContent = await FileSystemUtils.readFile(projectMdPath);\r\n projectInfo = this.extractProjectInfo(projectContent);\r\n }\r\n\r\n // Find all spec files\r\n const specFiles = await this.findSpecFiles(specsDir);\r\n\r\n if (specFiles.length === 0) {\r\n spinner.warn('No specs found. Create specs first using \"heraspec list --specs\".');\r\n return;\r\n }\r\n\r\n // Read and parse all specs\r\n const specs = await this.readSpecs(specFiles);\r\n\r\n // Generate test files\r\n const testFilesCreated = await this.generateTestFiles(specs, testDir, testType, projectInfo);\r\n\r\n spinner.succeed(`Generated ${testFilesCreated.length} test file(s) in ${testDir}`);\r\n console.log(chalk.gray(`\\nTest type: ${testType}`));\r\n console.log(chalk.gray(`Specs analyzed: ${specFiles.length}`));\r\n } catch (error) {\r\n spinner.fail(`Error: ${(error as Error).message}`);\r\n process.exitCode = 1;\r\n throw error;\r\n }\r\n }\r\n\r\n /**\r\n * Get test directory path based on project type and test type\r\n */\r\n private getTestDirectory(projectPath: string, testType: string): string {\r\n // Default test directories\r\n const testDirs: Record<string, string> = {\r\n unit: 'tests/unit',\r\n integration: 'tests/integration',\r\n e2e: 'tests/e2e',\r\n };\r\n\r\n const baseDir = testDirs[testType] || 'tests';\r\n return path.join(projectPath, baseDir);\r\n }\r\n\r\n /**\r\n * Extract project information from project.md\r\n */\r\n private extractProjectInfo(projectContent: string): { projectType?: string; stack?: string[] } {\r\n const info: { projectType?: string; stack?: string[] } = {};\r\n\r\n // Extract project type\r\n const projectTypeMatch = projectContent.match(/project[-\\s]type[s]?[:\\s]+([^\\n]+)/i);\r\n if (projectTypeMatch) {\r\n info.projectType = projectTypeMatch[1].trim();\r\n }\r\n\r\n // Extract tech stack\r\n const stackMatch = projectContent.match(/tech[-\\s]stack[:\\s]+([^\\n]+)/i);\r\n if (stackMatch) {\r\n info.stack = stackMatch[1]\r\n .split(',')\r\n .map(s => s.trim())\r\n .filter(s => s.length > 0);\r\n }\r\n\r\n return info;\r\n }\r\n\r\n /**\r\n * Find all spec files recursively\r\n */\r\n private async findSpecFiles(specsDir: string): Promise<string[]> {\r\n const specFiles: string[] = [];\r\n await this.findSpecFilesRecursive(specsDir, specFiles);\r\n return specFiles.sort();\r\n }\r\n\r\n /**\r\n * Recursively find spec files\r\n */\r\n private async findSpecFilesRecursive(dir: string, files: string[]): Promise<void> {\r\n const fs = await import('fs/promises');\r\n const entries = await fs.readdir(dir, { withFileTypes: true });\r\n\r\n for (const entry of entries) {\r\n const entryPath = path.join(dir, entry.name);\r\n\r\n if (entry.isDirectory()) {\r\n await this.findSpecFilesRecursive(entryPath, files);\r\n } else if (entry.name.endsWith('.md')) {\r\n files.push(entryPath);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Read all spec files\r\n */\r\n private async readSpecs(specFiles: string[]): Promise<Array<{ path: string; content: string; name: string }>> {\r\n const specs = [];\r\n\r\n for (const specFile of specFiles) {\r\n const content = await FileSystemUtils.readFile(specFile);\r\n const name = this.extractFeatureName(specFile, content);\r\n\r\n specs.push({\r\n path: specFile,\r\n content,\r\n name,\r\n });\r\n }\r\n\r\n return specs;\r\n }\r\n\r\n /**\r\n * Extract feature name from spec file\r\n */\r\n private extractFeatureName(filePath: string, content: string): string {\r\n // Try to get from first heading\r\n const headingMatch = content.match(/^#+\\s+(.+)$/m);\r\n if (headingMatch) {\r\n return headingMatch[1].trim();\r\n }\r\n\r\n // Fallback to filename\r\n return path.basename(filePath, '.md');\r\n }\r\n\r\n /**\r\n * Generate test files from specs\r\n */\r\n private async generateTestFiles(\r\n specs: Array<{ path: string; content: string; name: string }>,\r\n testDir: string,\r\n testType: string,\r\n projectInfo: { projectType?: string; stack?: string[] }\r\n ): Promise<string[]> {\r\n const createdFiles: string[] = [];\r\n\r\n for (const spec of specs) {\r\n const testFileName = this.getTestFileName(spec.name, testType, projectInfo);\r\n const testFilePath = path.join(testDir, testFileName);\r\n\r\n // Check if file already exists\r\n if (await FileSystemUtils.fileExists(testFilePath)) {\r\n console.log(chalk.yellow(` \u2139 Skipping ${path.basename(testFilePath)} - already exists.`));\r\n continue;\r\n }\r\n\r\n const testContent = this.generateTestContent(spec, testType, projectInfo);\r\n await FileSystemUtils.writeFile(testFilePath, testContent);\r\n createdFiles.push(testFilePath);\r\n }\r\n\r\n return createdFiles;\r\n }\r\n\r\n /**\r\n * Generate test file content\r\n */\r\n private generateTestContent(\r\n spec: { path: string; content: string; name: string },\r\n testType: string,\r\n projectInfo: { projectType?: string; stack?: string[] }\r\n ): string {\r\n const featureInfo = this.extractFeatureInfo(spec.content);\r\n const testFramework = this.determineTestFramework(projectInfo);\r\n\r\n const lines: string[] = [];\r\n\r\n // Header comment\r\n lines.push(`/**`);\r\n lines.push(` * ${testType.charAt(0).toUpperCase() + testType.slice(1)} tests for: ${spec.name}`);\r\n lines.push(` * Generated from spec: ${path.basename(spec.path)}`);\r\n lines.push(` */`);\r\n lines.push('');\r\n\r\n // Test framework setup\r\n if (testFramework === 'jest') {\r\n lines.push(`describe('${spec.name}', () => {`);\r\n lines.push(' // TODO: Implement test cases based on spec requirements');\r\n lines.push('');\r\n if (featureInfo.requirements.length > 0) {\r\n featureInfo.requirements.forEach((req, index) => {\r\n lines.push(` test('should ${req}', () => {`);\r\n lines.push(` // Test implementation needed`);\r\n lines.push(` expect(true).toBe(true);`);\r\n lines.push(` });`);\r\n if (index < featureInfo.requirements.length - 1) {\r\n lines.push('');\r\n }\r\n });\r\n }\r\n lines.push('});');\r\n } else if (testFramework === 'phpunit') {\r\n lines.push(`class ${this.toPascalCase(spec.name)}Test extends TestCase`);\r\n lines.push('{');\r\n lines.push(' // TODO: Implement test cases based on spec requirements');\r\n lines.push('');\r\n if (featureInfo.requirements.length > 0) {\r\n featureInfo.requirements.forEach((req, index) => {\r\n lines.push(` public function test_${this.toSnakeCase(req)}()`);\r\n lines.push(' {');\r\n lines.push(' // Test implementation needed');\r\n lines.push(' $this->assertTrue(true);');\r\n lines.push(' }');\r\n if (index < featureInfo.requirements.length - 1) {\r\n lines.push('');\r\n }\r\n });\r\n }\r\n lines.push('}');\r\n } else {\r\n // Generic test structure\r\n lines.push(`// ${testType.charAt(0).toUpperCase() + testType.slice(1)} tests for: ${spec.name}`);\r\n lines.push('');\r\n lines.push('// TODO: Implement test cases based on spec requirements');\r\n lines.push('');\r\n if (featureInfo.requirements.length > 0) {\r\n featureInfo.requirements.forEach((req) => {\r\n lines.push(`// Test: ${req}`);\r\n });\r\n }\r\n }\r\n\r\n return lines.join('\\n');\r\n }\r\n\r\n /**\r\n * Determine test framework based on project info\r\n */\r\n private determineTestFramework(projectInfo: { projectType?: string; stack?: string[] }): string {\r\n if (projectInfo.stack) {\r\n if (projectInfo.stack.some(s => s.toLowerCase().includes('php'))) {\r\n return 'phpunit';\r\n }\r\n if (projectInfo.stack.some(s => s.toLowerCase().includes('node') || s.toLowerCase().includes('javascript'))) {\r\n return 'jest';\r\n }\r\n }\r\n\r\n // Default to jest for modern projects\r\n return 'jest';\r\n }\r\n\r\n /**\r\n * Get test file name\r\n */\r\n private getTestFileName(featureName: string, testType: string, projectInfo: { projectType?: string; stack?: string[] }): string {\r\n const framework = this.determineTestFramework(projectInfo);\r\n const baseName = this.toKebabCase(featureName);\r\n\r\n if (framework === 'phpunit') {\r\n return `${this.toPascalCase(featureName)}Test.php`;\r\n } else if (framework === 'jest') {\r\n return `${baseName}.test.js`;\r\n }\r\n\r\n return `${baseName}.test.js`;\r\n }\r\n\r\n /**\r\n * Extract feature info from spec content\r\n */\r\n private extractFeatureInfo(content: string): { requirements: string[] } {\r\n const info: { requirements: string[] } = {\r\n requirements: [],\r\n };\r\n\r\n const lines = content.split('\\n');\r\n let inRequirements = false;\r\n\r\n for (const line of lines) {\r\n const trimmed = line.trim();\r\n\r\n if (trimmed.match(/^##+\\s+Requirements?/i)) {\r\n inRequirements = true;\r\n continue;\r\n } else if (trimmed.match(/^##+/) && inRequirements) {\r\n break;\r\n }\r\n\r\n if (inRequirements && trimmed.startsWith('-')) {\r\n const requirement = trimmed.replace(/^-\\s*/, '').trim();\r\n if (requirement) {\r\n info.requirements.push(requirement);\r\n }\r\n }\r\n }\r\n\r\n return info;\r\n }\r\n\r\n /**\r\n * Convert to kebab-case\r\n */\r\n private toKebabCase(str: string): string {\r\n return str\r\n .replace(/([a-z])([A-Z])/g, '$1-$2')\r\n .toLowerCase()\r\n .replace(/[^a-z0-9]+/g, '-')\r\n .replace(/^-|-$/g, '');\r\n }\r\n\r\n /**\r\n * Convert to PascalCase\r\n */\r\n private toPascalCase(str: string): string {\r\n return str\r\n .split(/[^a-zA-Z0-9]+/)\r\n .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\r\n .join('');\r\n }\r\n\r\n /**\r\n * Convert to snake_case\r\n */\r\n private toSnakeCase(str: string): string {\r\n return str\r\n .replace(/([a-z])([A-Z])/g, '$1_$2')\r\n .toLowerCase()\r\n .replace(/[^a-z0-9]+/g, '_')\r\n .replace(/^_|_$/g, '');\r\n }\r\n}\r\n\r\n", "/**\r\n * HeraSpec Make Code Command\r\n * Generates code skeletons from specs\r\n */\r\nimport path from 'path';\r\nimport chalk from 'chalk';\r\nimport ora from 'ora';\r\nimport { FileSystemUtils } from '../utils/file-system.js';\r\nimport { HERASPEC_DIR_NAME, SPECS_DIR_NAME, HERASPEC_MARKERS } from '../core/config.js';\r\nimport { MarkdownParser } from '../core/parsers/markdown-parser.js';\r\n\r\nexport class MakeCodeCommand {\r\n async execute(projectPath: string = '.', specName?: string): Promise<void> {\r\n const spinner = ora('Generating code from specs...').start();\r\n\r\n try {\r\n const resolvedPath = path.resolve(projectPath);\r\n const specsDir = path.join(resolvedPath, HERASPEC_DIR_NAME, SPECS_DIR_NAME);\r\n const projectMdPath = path.join(resolvedPath, HERASPEC_DIR_NAME, HERASPEC_MARKERS.PROJECT_MD);\r\n\r\n // Check if specs directory exists\r\n if (!(await FileSystemUtils.fileExists(specsDir))) {\r\n spinner.fail('Specs directory not found. Run \"heraspec init\" first.');\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n // Read project.md for context\r\n let projectInfo: { projectType?: string; stack?: string[] } = {};\r\n if (await FileSystemUtils.fileExists(projectMdPath)) {\r\n const projectContent = await FileSystemUtils.readFile(projectMdPath);\r\n projectInfo = this.extractProjectInfo(projectContent);\r\n }\r\n\r\n // Find spec files\r\n let specFiles: string[] = [];\r\n if (specName) {\r\n // Find specific spec\r\n const specPath = this.findSpecPath(specsDir, specName);\r\n if (specPath && (await FileSystemUtils.fileExists(specPath))) {\r\n specFiles = [specPath];\r\n } else {\r\n spinner.fail(`Spec \"${specName}\" not found`);\r\n process.exitCode = 1;\r\n return;\r\n }\r\n } else {\r\n // Find all specs\r\n specFiles = await this.findSpecFiles(specsDir);\r\n }\r\n\r\n if (specFiles.length === 0) {\r\n spinner.warn('No specs found. Create specs first using \"heraspec list --specs\".');\r\n return;\r\n }\r\n\r\n // Read and parse specs\r\n const specs = await this.readSpecs(specFiles);\r\n\r\n // Generate code files\r\n const generatedFiles = await this.generateCodeFiles(specs, resolvedPath, projectInfo);\r\n\r\n spinner.succeed(`Generated ${generatedFiles.length} code file(s)`);\r\n console.log(chalk.gray(`\\nSpecs analyzed: ${specFiles.length}`));\r\n generatedFiles.forEach((file: string) => {\r\n console.log(chalk.cyan(` \u2713 ${path.relative(resolvedPath, file)}`));\r\n });\r\n } catch (error) {\r\n spinner.fail(`Error: ${(error as Error).message}`);\r\n process.exitCode = 1;\r\n throw error;\r\n }\r\n }\r\n\r\n private extractProjectInfo(content: string): { projectType?: string; stack?: string[] } {\r\n const projectTypeMatch = content.match(/project[-\\s]type[s]?[:\\s]+([^\\n]+)/i);\r\n const stackMatch = content.match(/tech[-\\s]stack[:\\s]+([^\\n]+)/i);\r\n\r\n return {\r\n projectType: projectTypeMatch ? projectTypeMatch[1].trim().split(',')[0].trim() : undefined,\r\n stack: stackMatch ? stackMatch[1].split(',').map(s => s.trim()).filter(Boolean) : undefined,\r\n };\r\n }\r\n\r\n private findSpecPath(specsDir: string, specName: string): string | null {\r\n // Try direct path first\r\n const directPath = path.join(specsDir, `${specName}.md`);\r\n // Try nested path\r\n const nestedPath = path.join(specsDir, specName, 'spec.md');\r\n return directPath; // Return first option, caller will check existence\r\n }\r\n\r\n private async findSpecFiles(specsDir: string): Promise<string[]> {\r\n const specFiles: string[] = [];\r\n await this.findSpecFilesRecursive(specsDir, specFiles);\r\n return specFiles.sort();\r\n }\r\n\r\n private async findSpecFilesRecursive(dir: string, files: string[]): Promise<void> {\r\n const fs = await import('fs/promises');\r\n const entries = await fs.readdir(dir, { withFileTypes: true });\r\n\r\n for (const entry of entries) {\r\n const entryPath = path.join(dir, entry.name);\r\n\r\n if (entry.isDirectory()) {\r\n await this.findSpecFilesRecursive(entryPath, files);\r\n } else if (entry.name.endsWith('.md') && entry.name !== 'README.md') {\r\n files.push(entryPath);\r\n }\r\n }\r\n }\r\n\r\n private async readSpecs(specFiles: string[]): Promise<Array<{ path: string; content: string; name: string; parsed: any }>> {\r\n const specs = [];\r\n\r\n for (const specFile of specFiles) {\r\n const content = await FileSystemUtils.readFile(specFile);\r\n const parser = new MarkdownParser(content);\r\n const specName = path.basename(specFile, '.md');\r\n\r\n try {\r\n const parsed = parser.parseSpec(specName);\r\n specs.push({\r\n path: specFile,\r\n content,\r\n name: parsed.name,\r\n parsed,\r\n });\r\n } catch (error) {\r\n console.warn(chalk.yellow(`Warning: Could not parse spec file ${specFile}. Skipping.`));\r\n }\r\n }\r\n\r\n return specs;\r\n }\r\n\r\n private async generateCodeFiles(\r\n specs: Array<{ path: string; content: string; name: string; parsed: any }>,\r\n projectPath: string,\r\n projectInfo: { projectType?: string; stack?: string[] }\r\n ): Promise<string[]> {\r\n const generatedFiles: string[] = [];\r\n const projectType = projectInfo.projectType || 'generic-webapp';\r\n\r\n for (const spec of specs) {\r\n const codeContent = this.generateCodeContent(spec, projectType, projectInfo);\r\n const outputPath = this.getOutputPath(projectPath, spec.name, projectType);\r\n \r\n // Ensure directory exists\r\n await FileSystemUtils.createDirectory(path.dirname(outputPath));\r\n await FileSystemUtils.writeFile(outputPath, codeContent);\r\n generatedFiles.push(outputPath);\r\n }\r\n\r\n return generatedFiles;\r\n }\r\n\r\n private getOutputPath(projectPath: string, specName: string, projectType: string): string {\r\n // Generate appropriate path based on project type\r\n const sanitizedName = specName.toLowerCase().replace(/[^a-z0-9-]/g, '-');\r\n \r\n if (projectType.includes('wordpress-plugin')) {\r\n return path.join(projectPath, 'includes', `class-${sanitizedName}.php`);\r\n } else if (projectType.includes('perfex-module')) {\r\n return path.join(projectPath, 'modules', sanitizedName, `${sanitizedName}.php`);\r\n } else if (projectType.includes('laravel')) {\r\n return path.join(projectPath, 'app', 'Services', `${this.toPascalCase(sanitizedName)}Service.php`);\r\n } else if (projectType.includes('node')) {\r\n return path.join(projectPath, 'src', 'services', `${sanitizedName}.js`);\r\n } else {\r\n // Generic\r\n return path.join(projectPath, 'src', `${sanitizedName}.ts`);\r\n }\r\n }\r\n\r\n private generateCodeContent(\r\n spec: { path: string; content: string; name: string; parsed: any },\r\n projectType: string,\r\n projectInfo: { projectType?: string; stack?: string[] }\r\n ): string {\r\n const lines: string[] = [];\r\n const className = this.toPascalCase(spec.name.replace(/[^a-zA-Z0-9]/g, ''));\r\n\r\n // Header comment\r\n lines.push(`/**`);\r\n lines.push(` * ${spec.name}`);\r\n lines.push(` * Generated from spec: ${path.basename(spec.path)}`);\r\n lines.push(` *`);\r\n lines.push(` * ${spec.parsed.overview || 'Generated code skeleton'}`);\r\n lines.push(` */`);\r\n lines.push('');\r\n\r\n if (projectType.includes('wordpress-plugin') || projectType.includes('perfex-module')) {\r\n // PHP class\r\n lines.push(`<?php`);\r\n lines.push('');\r\n lines.push(`class ${className} {`);\r\n lines.push('');\r\n \r\n // Add methods based on requirements\r\n spec.parsed.requirements.forEach((req: any) => {\r\n const methodName = this.toCamelCase(req.name.replace(/[^a-zA-Z0-9]/g, ''));\r\n lines.push(` /**`);\r\n lines.push(` * ${req.description || req.name}`);\r\n lines.push(` */`);\r\n lines.push(` public function ${methodName}() {`);\r\n lines.push(` // TODO: Implement ${req.name}`);\r\n lines.push(` }`);\r\n lines.push('');\r\n });\r\n \r\n lines.push('}');\r\n } else if (projectType.includes('laravel')) {\r\n // PHP Service class\r\n lines.push(`<?php`);\r\n lines.push('');\r\n lines.push(`namespace App\\\\Services;`);\r\n lines.push('');\r\n lines.push(`class ${className}Service {`);\r\n lines.push('');\r\n \r\n spec.parsed.requirements.forEach((req: any) => {\r\n const methodName = this.toCamelCase(req.name.replace(/[^a-zA-Z0-9]/g, ''));\r\n lines.push(` /**`);\r\n lines.push(` * ${req.description || req.name}`);\r\n lines.push(` */`);\r\n lines.push(` public function ${methodName}() {`);\r\n lines.push(` // TODO: Implement ${req.name}`);\r\n lines.push(` }`);\r\n lines.push('');\r\n });\r\n \r\n lines.push('}');\r\n } else if (projectType.includes('node')) {\r\n // JavaScript/TypeScript\r\n lines.push(`/**`);\r\n lines.push(` * ${spec.name} service`);\r\n lines.push(` */`);\r\n lines.push('');\r\n lines.push(`class ${className} {`);\r\n lines.push('');\r\n \r\n spec.parsed.requirements.forEach((req: any) => {\r\n const methodName = this.toCamelCase(req.name.replace(/[^a-zA-Z0-9]/g, ''));\r\n lines.push(` /**`);\r\n lines.push(` * ${req.description || req.name}`);\r\n lines.push(` */`);\r\n lines.push(` ${methodName}() {`);\r\n lines.push(` // TODO: Implement ${req.name}`);\r\n lines.push(` }`);\r\n lines.push('');\r\n });\r\n \r\n lines.push('}');\r\n lines.push('');\r\n lines.push(`module.exports = ${className};`);\r\n } else {\r\n // Generic TypeScript\r\n lines.push(`export class ${className} {`);\r\n lines.push('');\r\n \r\n spec.parsed.requirements.forEach((req: any) => {\r\n const methodName = this.toCamelCase(req.name.replace(/[^a-zA-Z0-9]/g, ''));\r\n lines.push(` /**`);\r\n lines.push(` * ${req.description || req.name}`);\r\n lines.push(` */`);\r\n lines.push(` ${methodName}(): void {`);\r\n lines.push(` // TODO: Implement ${req.name}`);\r\n lines.push(` }`);\r\n lines.push('');\r\n });\r\n \r\n lines.push('}');\r\n }\r\n\r\n lines.push('');\r\n lines.push(`// Generated by HeraSpec - Update this file based on implementation requirements`);\r\n\r\n return lines.join('\\n');\r\n }\r\n\r\n private toPascalCase(str: string): string {\r\n return str\r\n .replace(/[^a-zA-Z0-9]/g, ' ')\r\n .split(' ')\r\n .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\r\n .join('');\r\n }\r\n\r\n private toCamelCase(str: string): string {\r\n const pascal = this.toPascalCase(str);\r\n return pascal.charAt(0).toLowerCase() + pascal.slice(1);\r\n }\r\n}\r\n", "/**\r\n * HeraSpec Suggest Command\r\n * Analyzes project and suggests new features\r\n */\r\nimport path from 'path';\r\nimport chalk from 'chalk';\r\nimport ora from 'ora';\r\nimport { FileSystemUtils } from '../utils/file-system.js';\r\nimport { HERASPEC_DIR_NAME, SPECS_DIR_NAME, HERASPEC_MARKERS } from '../core/config.js';\r\n\r\nexport class SuggestCommand {\r\n async execute(projectPath: string = '.'): Promise<void> {\r\n const spinner = ora('Analyzing project and generating suggestions...').start();\r\n\r\n try {\r\n const resolvedPath = path.resolve(projectPath);\r\n const specsDir = path.join(resolvedPath, HERASPEC_DIR_NAME, SPECS_DIR_NAME);\r\n const suggestionsDir = path.join(resolvedPath, HERASPEC_DIR_NAME, 'suggestions');\r\n const projectMdPath = path.join(resolvedPath, HERASPEC_DIR_NAME, HERASPEC_MARKERS.PROJECT_MD);\r\n\r\n // Check if specs directory exists\r\n if (!(await FileSystemUtils.fileExists(specsDir))) {\r\n spinner.fail('Specs directory not found. Run \"heraspec init\" first.');\r\n process.exitCode = 1;\r\n return;\r\n }\r\n\r\n // Ensure suggestions directory exists\r\n await FileSystemUtils.createDirectory(suggestionsDir);\r\n\r\n // Read project.md if exists\r\n let projectInfo: { name?: string; projectType?: string; stack?: string[] } = {};\r\n if (await FileSystemUtils.fileExists(projectMdPath)) {\r\n const projectContent = await FileSystemUtils.readFile(projectMdPath);\r\n projectInfo = this.extractProjectInfo(projectContent);\r\n }\r\n\r\n // Find all spec files\r\n const specFiles = await this.findSpecFiles(specsDir);\r\n\r\n // Read existing specs\r\n const specs = specFiles.length > 0 ? await this.readSpecs(specFiles) : [];\r\n\r\n // Generate suggestions\r\n const suggestions = this.generateSuggestions(specs, projectInfo);\r\n\r\n // Write suggestions file\r\n const suggestionsFilePath = path.join(suggestionsDir, 'feature-suggestions.md');\r\n const suggestionsContent = this.formatSuggestions(suggestions, projectInfo);\r\n await FileSystemUtils.writeFile(suggestionsFilePath, suggestionsContent);\r\n\r\n spinner.succeed(`Feature suggestions generated: ${suggestionsFilePath}`);\r\n console.log(chalk.gray(`\\nFound ${specs.length} existing feature(s)`));\r\n console.log(chalk.gray(`Generated ${suggestions.length} suggestion(s)`));\r\n } catch (error) {\r\n spinner.fail(`Error: ${(error as Error).message}`);\r\n process.exitCode = 1;\r\n throw error;\r\n }\r\n }\r\n\r\n /**\r\n * Extract project information from project.md\r\n */\r\n private extractProjectInfo(projectContent: string): { name?: string; projectType?: string; stack?: string[] } {\r\n const info: { name?: string; projectType?: string; stack?: string[] } = {};\r\n\r\n // Extract project name\r\n const nameMatch = projectContent.match(/^#\\s+(.+)$/m);\r\n if (nameMatch) {\r\n info.name = nameMatch[1].trim();\r\n }\r\n\r\n // Extract project type\r\n const projectTypeMatch = projectContent.match(/project[-\\s]type[s]?[:\\s]+([^\\n]+)/i);\r\n if (projectTypeMatch) {\r\n info.projectType = projectTypeMatch[1].trim();\r\n }\r\n\r\n // Extract tech stack\r\n const stackMatch = projectContent.match(/tech[-\\s]stack[:\\s]+([^\\n]+)/i);\r\n if (stackMatch) {\r\n info.stack = stackMatch[1]\r\n .split(',')\r\n .map(s => s.trim())\r\n .filter(s => s.length > 0);\r\n }\r\n\r\n return info;\r\n }\r\n\r\n /**\r\n * Find all spec files recursively\r\n */\r\n private async findSpecFiles(specsDir: string): Promise<string[]> {\r\n const specFiles: string[] = [];\r\n await this.findSpecFilesRecursive(specsDir, specFiles);\r\n return specFiles.sort();\r\n }\r\n\r\n /**\r\n * Recursively find spec files\r\n */\r\n private async findSpecFilesRecursive(dir: string, files: string[]): Promise<void> {\r\n const fs = await import('fs/promises');\r\n const entries = await fs.readdir(dir, { withFileTypes: true });\r\n\r\n for (const entry of entries) {\r\n const entryPath = path.join(dir, entry.name);\r\n\r\n if (entry.isDirectory()) {\r\n await this.findSpecFilesRecursive(entryPath, files);\r\n } else if (entry.name.endsWith('.md')) {\r\n files.push(entryPath);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Read all spec files\r\n */\r\n private async readSpecs(specFiles: string[]): Promise<Array<{ path: string; content: string; name: string }>> {\r\n const specs = [];\r\n\r\n for (const specFile of specFiles) {\r\n const content = await FileSystemUtils.readFile(specFile);\r\n const name = this.extractFeatureName(specFile, content);\r\n\r\n specs.push({\r\n path: specFile,\r\n content,\r\n name,\r\n });\r\n }\r\n\r\n return specs;\r\n }\r\n\r\n /**\r\n * Extract feature name from spec file\r\n */\r\n private extractFeatureName(filePath: string, content: string): string {\r\n const headingMatch = content.match(/^#+\\s+(.+)$/m);\r\n if (headingMatch) {\r\n return headingMatch[1].trim();\r\n }\r\n return path.basename(filePath, '.md');\r\n }\r\n\r\n /**\r\n * Generate feature suggestions based on existing specs\r\n */\r\n private generateSuggestions(\r\n specs: Array<{ path: string; content: string; name: string }>,\r\n projectInfo: { name?: string; projectType?: string; stack?: string[] }\r\n ): Array<{ title: string; description: string; category: string; integrationPoints: string[] }> {\r\n const suggestions: Array<{ title: string; description: string; category: string; integrationPoints: string[] }> = [];\r\n\r\n // Analyze existing features and suggest enhancements\r\n const existingFeatures = specs.map(s => s.name.toLowerCase());\r\n\r\n // Common suggestion patterns based on project type\r\n if (projectInfo.projectType?.toLowerCase().includes('plugin') || projectInfo.projectType?.toLowerCase().includes('module')) {\r\n if (!existingFeatures.some(f => f.includes('settings') || f.includes('config'))) {\r\n suggestions.push({\r\n title: 'Settings/Configuration Management',\r\n description: 'Add a centralized settings management feature to allow users to configure plugin/module behavior.',\r\n category: 'Configuration',\r\n integrationPoints: ['Admin interface', 'Database storage'],\r\n });\r\n }\r\n\r\n if (!existingFeatures.some(f => f.includes('report') || f.includes('analytics'))) {\r\n suggestions.push({\r\n title: 'Reporting and Analytics',\r\n description: 'Add reporting functionality to track usage, generate analytics, and provide insights.',\r\n category: 'Analytics',\r\n integrationPoints: ['Data collection', 'Dashboard'],\r\n });\r\n }\r\n }\r\n\r\n // General suggestions\r\n if (!existingFeatures.some(f => f.includes('export') || f.includes('import'))) {\r\n suggestions.push({\r\n title: 'Data Import/Export',\r\n description: 'Add functionality to import and export data in various formats (CSV, JSON, XML).',\r\n category: 'Data Management',\r\n integrationPoints: ['File handling', 'Data processing'],\r\n });\r\n }\r\n\r\n if (!existingFeatures.some(f => f.includes('search') || f.includes('filter'))) {\r\n suggestions.push({\r\n title: 'Advanced Search and Filtering',\r\n description: 'Implement advanced search and filtering capabilities to help users find information quickly.',\r\n category: 'User Experience',\r\n integrationPoints: ['Search interface', 'Data indexing'],\r\n });\r\n }\r\n\r\n if (!existingFeatures.some(f => f.includes('notification') || f.includes('alert'))) {\r\n suggestions.push({\r\n title: 'Notifications and Alerts',\r\n description: 'Add notification system to alert users about important events and updates.',\r\n category: 'Communication',\r\n integrationPoints: ['Event system', 'User preferences'],\r\n });\r\n }\r\n\r\n return suggestions;\r\n }\r\n\r\n /**\r\n * Format suggestions as markdown\r\n */\r\n private formatSuggestions(\r\n suggestions: Array<{ title: string; description: string; category: string; integrationPoints: string[] }>,\r\n projectInfo: { name?: string; projectType?: string; stack?: string[] }\r\n ): string {\r\n const lines: string[] = [];\r\n\r\n // Header\r\n lines.push('# Feature Suggestions');\r\n lines.push('');\r\n lines.push(`Generated for: ${projectInfo.name || 'Project'}`);\r\n lines.push(`Project Type: ${projectInfo.projectType || 'Not specified'}`);\r\n lines.push(`Generated on: ${new Date().toISOString()}`);\r\n lines.push('');\r\n lines.push('---');\r\n lines.push('');\r\n\r\n // Overview\r\n lines.push('## Overview');\r\n lines.push('');\r\n lines.push(`This document contains ${suggestions.length} feature suggestions that could enhance the project.`);\r\n lines.push('Each suggestion includes integration points and considerations for implementation.');\r\n lines.push('');\r\n lines.push('---');\r\n lines.push('');\r\n\r\n // Group by category\r\n const byCategory: Record<string, Array<{ title: string; description: string; category: string; integrationPoints: string[] }>> = {};\r\n suggestions.forEach(suggestion => {\r\n if (!byCategory[suggestion.category]) {\r\n byCategory[suggestion.category] = [];\r\n }\r\n byCategory[suggestion.category].push(suggestion);\r\n });\r\n\r\n // Write suggestions by category\r\n Object.entries(byCategory).forEach(([category, categorySuggestions]) => {\r\n lines.push(`## ${category}`);\r\n lines.push('');\r\n categorySuggestions.forEach((suggestion, index) => {\r\n lines.push(`### ${index + 1}. ${suggestion.title}`);\r\n lines.push('');\r\n lines.push(suggestion.description);\r\n lines.push('');\r\n if (suggestion.integrationPoints.length > 0) {\r\n lines.push('**Integration Points:**');\r\n lines.push('');\r\n suggestion.integrationPoints.forEach(point => {\r\n lines.push(`- ${point}`);\r\n });\r\n lines.push('');\r\n }\r\n if (index < categorySuggestions.length - 1) {\r\n lines.push('---');\r\n lines.push('');\r\n }\r\n });\r\n lines.push('');\r\n });\r\n\r\n // Footer\r\n lines.push('---');\r\n lines.push('');\r\n lines.push('*These suggestions are generated based on analysis of existing features and common patterns.*');\r\n lines.push('*Review and prioritize suggestions based on project requirements and goals.*');\r\n lines.push('');\r\n\r\n return lines.join('\\n');\r\n }\r\n}\r\n\r\n", "/**\n * HeraSpec Hotfix Command\n * Fast-track shortcut to log a bugfix without full spec workflow\n */\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { MemoryCommand } from './memory.js';\n\nexport class HotfixCommand {\n /**\n * Execute the hotfix command\n */\n async execute(title: string, options: { narrative?: string }, projectPath: string = '.'): Promise<void> {\n if (!title) {\n console.error(chalk.red('Error: A title is required for a hotfix.'));\n console.error(chalk.gray('Example: heraspec hotfix \"Fixed login typo\" -n \"Changed usr to user in auth.ts\"'));\n process.exitCode = 1;\n return;\n }\n\n let narrative = options.narrative;\n\n // Interactive prompt for narrative if not provided\n if (!narrative) {\n try {\n const { input } = await import('@inquirer/prompts');\n narrative = await input({\n message: 'Describe the fix (narrative):',\n validate: (value) => value.trim().length > 0 || 'Narrative cannot be empty',\n });\n } catch (error) {\n console.log(chalk.gray('Aborted.'));\n process.exitCode = 1;\n return;\n }\n }\n\n console.log(chalk.cyan(`\\n\uD83D\uDE91 Applying Hotfix...`));\n \n // We delegate directly to memory log\n const memory = new MemoryCommand();\n await memory.log({\n type: 'bugfix',\n title,\n narrative,\n concepts: 'hotfix', // add a hotfix tag\n }, projectPath);\n \n console.log(chalk.green('\\n\u2705 Hotfix logged to project memory successfully.'));\n }\n}\n", "/**\n * HeraSpec Explore Command\n * CLI commands for smart code exploration\n */\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport path from 'path';\nimport { CodeParser } from '../core/parsers/code-parser.js';\nimport { FileSystemUtils } from '../utils/file-system.js';\n\nexport class ExploreCommand {\n /**\n * heraspec explore outline <file> - Show structural skeleton\n */\n async outline(filePath: string): Promise<void> {\n const spinner = ora(`Analyzing ${filePath}...`).start();\n\n try {\n const absPath = path.resolve(filePath);\n\n if (!(await FileSystemUtils.fileExists(absPath))) {\n spinner.fail(`File not found: ${filePath}`);\n process.exitCode = 1;\n return;\n }\n\n const outline = await CodeParser.outline(absPath);\n spinner.stop();\n\n console.log('\\n' + CodeParser.formatOutline(outline));\n console.log(`\\n${chalk.gray(`Total: ${outline.symbols.length} symbols | ~${outline.estimatedTokens} tokens (full file) | Outline: ~${outline.symbols.length * 15} tokens`)}\\n`);\n } catch (error) {\n spinner.fail(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exitCode = 1;\n }\n }\n\n /**\n * heraspec explore search <query> [path] - Search symbols across codebase\n */\n async search(query: string, searchPath: string = '.', options: { limit?: number } = {}): Promise<void> {\n const spinner = ora(`Searching for \"${query}\" in ${searchPath}...`).start();\n\n try {\n const absPath = path.resolve(searchPath);\n const results = await CodeParser.search(query, absPath, options.limit || 20);\n\n spinner.stop();\n\n if (results.length === 0) {\n console.log(chalk.yellow(`\\nNo symbols found matching \"${query}\" in ${searchPath}\\n`));\n return;\n }\n\n console.log(`\\n## Symbol Search: \"${query}\" (${results.length} results)\\n`);\n console.log('| Rel | Type | Name | File | Lines |');\n console.log('|-----|------|------|------|-------|');\n\n for (const { symbol, relevance } of results) {\n const relPath = path.relative(process.cwd(), symbol.filePath);\n const typeIcons: Record<string, string> = {\n class: '\uD83C\uDFDB\uFE0F', interface: '\uD83D\uDD37', type: '\uD83D\uDD39', enum: '\uD83D\uDCCB',\n function: '\u26A1', method: '\u21B3', variable: '\uD83D\uDCCC', export: '\uD83D\uDCE4',\n };\n const icon = typeIcons[symbol.type] || '\u2022';\n console.log(`| ${relevance}% | ${icon} ${symbol.type} | ${symbol.name} | ${relPath} | L${symbol.startLine}-${symbol.endLine} |`);\n }\n\n console.log(`\\n${chalk.gray('Use `heraspec explore unfold <file> <symbol>` to see full source.')}\\n`);\n } catch (error) {\n spinner.fail(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exitCode = 1;\n }\n }\n\n /**\n * heraspec explore unfold <file> <symbol> - Show full implementation of a symbol\n */\n async unfold(filePath: string, symbolName: string): Promise<void> {\n const spinner = ora(`Extracting ${symbolName} from ${filePath}...`).start();\n\n try {\n const absPath = path.resolve(filePath);\n\n if (!(await FileSystemUtils.fileExists(absPath))) {\n spinner.fail(`File not found: ${filePath}`);\n process.exitCode = 1;\n return;\n }\n\n const result = await CodeParser.unfold(absPath, symbolName);\n spinner.stop();\n\n if (!result.symbol) {\n console.log(chalk.yellow(`\\nSymbol \"${symbolName}\" not found in ${filePath}`));\n console.log(chalk.gray('Available symbols:'));\n\n const outline = await CodeParser.outline(absPath);\n for (const sym of outline.symbols) {\n console.log(` ${sym.type}: ${sym.name} (L${sym.startLine}-${sym.endLine})`);\n }\n console.log('');\n process.exitCode = 1;\n return;\n }\n\n const relPath = path.relative(process.cwd(), absPath);\n const outline = await CodeParser.outline(absPath);\n\n console.log(`\\n## ${result.symbol.type}: ${result.symbol.name}`);\n console.log(`*${relPath}:L${result.symbol.startLine}-${result.symbol.endLine} | ~${result.estimatedTokens} tokens (vs ~${outline.estimatedTokens} full file)*\\n`);\n console.log('```' + (outline.language || ''));\n console.log(result.source);\n console.log('```\\n');\n } catch (error) {\n spinner.fail(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exitCode = 1;\n }\n }\n}\n", "/**\n * HeraSpec Code Parser\n * Regex-based multi-language symbol extraction (no tree-sitter dependency)\n * Supports: TypeScript, JavaScript, Python, PHP, Go, Rust, Java, C#\n */\nimport { promises as fs } from 'fs';\nimport path from 'path';\n\nexport interface SymbolInfo {\n name: string;\n type: 'function' | 'class' | 'method' | 'interface' | 'type' | 'export' | 'variable' | 'enum';\n signature: string;\n startLine: number;\n endLine: number;\n filePath: string;\n}\n\nexport interface FileOutline {\n filePath: string;\n language: string;\n symbols: SymbolInfo[];\n lineCount: number;\n estimatedTokens: number;\n}\n\n// Language detection by extension\nconst LANGUAGE_MAP: Record<string, string> = {\n '.ts': 'typescript', '.tsx': 'typescript',\n '.js': 'javascript', '.jsx': 'javascript', '.mjs': 'javascript', '.cjs': 'javascript',\n '.py': 'python',\n '.php': 'php',\n '.go': 'go',\n '.rs': 'rust',\n '.java': 'java',\n '.cs': 'csharp',\n '.rb': 'ruby',\n '.vue': 'vue',\n '.svelte': 'svelte',\n};\n\n// Symbol extraction patterns per language\nconst LANGUAGE_PATTERNS: Record<string, Array<{ regex: RegExp; type: SymbolInfo['type'] }>> = {\n typescript: [\n { regex: /^(?:export\\s+)?(?:abstract\\s+)?class\\s+(\\w+)/gm, type: 'class' },\n { regex: /^(?:export\\s+)?interface\\s+(\\w+)/gm, type: 'interface' },\n { regex: /^(?:export\\s+)?type\\s+(\\w+)/gm, type: 'type' },\n { regex: /^(?:export\\s+)?enum\\s+(\\w+)/gm, type: 'enum' },\n { regex: /^(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)/gm, type: 'function' },\n { regex: /^(?:export\\s+)?const\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\(/gm, type: 'function' },\n { regex: /^\\s+(?:public|private|protected|static|async|readonly)\\s+(?:async\\s+)?(\\w+)\\s*\\(/gm, type: 'method' },\n { regex: /^(?:export\\s+)?(?:const|let|var)\\s+(\\w+)\\s*[=:]/gm, type: 'variable' },\n ],\n javascript: [\n { regex: /^(?:export\\s+)?class\\s+(\\w+)/gm, type: 'class' },\n { regex: /^(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)/gm, type: 'function' },\n { regex: /^(?:export\\s+)?const\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\(/gm, type: 'function' },\n { regex: /^\\s+(\\w+)\\s*\\([^)]*\\)\\s*\\{/gm, type: 'method' },\n { regex: /^(?:export\\s+)?(?:const|let|var)\\s+(\\w+)\\s*=/gm, type: 'variable' },\n ],\n python: [\n { regex: /^class\\s+(\\w+)/gm, type: 'class' },\n { regex: /^(?:async\\s+)?def\\s+(\\w+)/gm, type: 'function' },\n { regex: /^\\s+(?:async\\s+)?def\\s+(\\w+)/gm, type: 'method' },\n { regex: /^(\\w+)\\s*=\\s*/gm, type: 'variable' },\n ],\n php: [\n { regex: /^(?:\\s*(?:abstract|final)\\s+)?class\\s+(\\w+)/gm, type: 'class' },\n { regex: /^(?:\\s*interface\\s+)(\\w+)/gm, type: 'interface' },\n { regex: /^(?:\\s*(?:public|private|protected|static)\\s+)*function\\s+(\\w+)/gm, type: 'function' },\n ],\n go: [\n { regex: /^type\\s+(\\w+)\\s+struct\\b/gm, type: 'class' },\n { regex: /^type\\s+(\\w+)\\s+interface\\b/gm, type: 'interface' },\n { regex: /^func\\s+(?:\\([^)]+\\)\\s+)?(\\w+)/gm, type: 'function' },\n ],\n rust: [\n { regex: /^(?:pub\\s+)?struct\\s+(\\w+)/gm, type: 'class' },\n { regex: /^(?:pub\\s+)?trait\\s+(\\w+)/gm, type: 'interface' },\n { regex: /^(?:pub\\s+)?enum\\s+(\\w+)/gm, type: 'enum' },\n { regex: /^(?:pub\\s+)?(?:async\\s+)?fn\\s+(\\w+)/gm, type: 'function' },\n { regex: /^\\s+(?:pub\\s+)?(?:async\\s+)?fn\\s+(\\w+)/gm, type: 'method' },\n ],\n java: [\n { regex: /^(?:\\s*(?:public|private|protected)\\s+)?(?:abstract\\s+)?class\\s+(\\w+)/gm, type: 'class' },\n { regex: /^(?:\\s*(?:public|private|protected)\\s+)?interface\\s+(\\w+)/gm, type: 'interface' },\n { regex: /^(?:\\s*(?:public|private|protected|static)\\s+)+[\\w<>\\[\\]]+\\s+(\\w+)\\s*\\(/gm, type: 'method' },\n ],\n csharp: [\n { regex: /^(?:\\s*(?:public|private|protected|internal)\\s+)?(?:abstract|static|sealed|partial)?\\s*class\\s+(\\w+)/gm, type: 'class' },\n { regex: /^(?:\\s*(?:public|private|protected|internal)\\s+)?interface\\s+(\\w+)/gm, type: 'interface' },\n { regex: /^(?:\\s*(?:public|private|protected|internal|static)\\s+)+[\\w<>\\[\\]]+\\s+(\\w+)\\s*\\(/gm, type: 'method' },\n ],\n};\n\n// Use same patterns as base language for derivatives\nLANGUAGE_PATTERNS['vue'] = LANGUAGE_PATTERNS['typescript'];\nLANGUAGE_PATTERNS['svelte'] = LANGUAGE_PATTERNS['typescript'];\nLANGUAGE_PATTERNS['ruby'] = LANGUAGE_PATTERNS['python']; // Similar enough\n\nexport class CodeParser {\n /**\n * Get structural outline of a file (symbols without full source)\n */\n static async outline(filePath: string): Promise<FileOutline> {\n const content = await fs.readFile(filePath, 'utf-8');\n const ext = path.extname(filePath).toLowerCase();\n const language = LANGUAGE_MAP[ext] || 'unknown';\n const lines = content.split('\\n');\n const symbols = CodeParser.extractSymbols(content, language, filePath);\n\n return {\n filePath,\n language,\n symbols,\n lineCount: lines.length,\n estimatedTokens: Math.ceil(content.length / 4),\n };\n }\n\n /**\n * Extract all symbols from file content\n */\n static extractSymbols(content: string, language: string, filePath: string): SymbolInfo[] {\n const patterns = LANGUAGE_PATTERNS[language];\n if (!patterns) return [];\n\n const lines = content.split('\\n');\n const symbols: SymbolInfo[] = [];\n const seenPositions = new Set<string>(); // Prevent duplicates\n\n for (const { regex, type } of patterns) {\n // Reset regex state\n const re = new RegExp(regex.source, regex.flags);\n let match;\n\n while ((match = re.exec(content)) !== null) {\n const name = match[1];\n if (!name || name.length < 2) continue;\n\n // Skip common false positives\n if (['if', 'for', 'while', 'switch', 'catch', 'return', 'new', 'this', 'super'].includes(name)) {\n continue;\n }\n\n const startLine = content.substring(0, match.index).split('\\n').length;\n const endLine = CodeParser.findEndLine(lines, startLine - 1, language);\n const signature = match[0].trim();\n\n const posKey = `${startLine}:${name}`;\n if (seenPositions.has(posKey)) continue;\n seenPositions.add(posKey);\n\n symbols.push({\n name,\n type,\n signature,\n startLine,\n endLine,\n filePath,\n });\n }\n }\n\n // Sort by line number\n symbols.sort((a, b) => a.startLine - b.startLine);\n return symbols;\n }\n\n /**\n * Unfold: extract the full source of a specific symbol\n */\n static async unfold(filePath: string, symbolName: string): Promise<{\n symbol: SymbolInfo | null;\n source: string;\n estimatedTokens: number;\n }> {\n const outline = await CodeParser.outline(filePath);\n const symbol = outline.symbols.find(s => s.name === symbolName);\n\n if (!symbol) {\n return { symbol: null, source: '', estimatedTokens: 0 };\n }\n\n const content = await fs.readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n const source = lines.slice(symbol.startLine - 1, symbol.endLine).join('\\n');\n\n return {\n symbol,\n source,\n estimatedTokens: Math.ceil(source.length / 4),\n };\n }\n\n /**\n * Search for symbols across a directory\n */\n static async search(query: string, searchPath: string, maxResults: number = 20): Promise<Array<{\n symbol: SymbolInfo;\n relevance: number;\n }>> {\n const results: Array<{ symbol: SymbolInfo; relevance: number }> = [];\n const queryLower = query.toLowerCase();\n\n await CodeParser.walkDir(searchPath, async (filePath) => {\n const ext = path.extname(filePath).toLowerCase();\n if (!LANGUAGE_MAP[ext]) return;\n\n try {\n const outline = await CodeParser.outline(filePath);\n for (const symbol of outline.symbols) {\n const nameLower = symbol.name.toLowerCase();\n const sigLower = symbol.signature.toLowerCase();\n\n // Simple relevance scoring\n let relevance = 0;\n if (nameLower === queryLower) relevance = 100;\n else if (nameLower.startsWith(queryLower)) relevance = 80;\n else if (nameLower.includes(queryLower)) relevance = 60;\n else if (sigLower.includes(queryLower)) relevance = 40;\n\n if (relevance > 0) {\n results.push({ symbol, relevance });\n }\n }\n } catch { /* skip unreadable files */ }\n });\n\n return results\n .sort((a, b) => b.relevance - a.relevance)\n .slice(0, maxResults);\n }\n\n /**\n * Format outline as markdown\n */\n static formatOutline(outline: FileOutline): string {\n const lines: string[] = [];\n const relPath = path.relative(process.cwd(), outline.filePath);\n\n lines.push(`## \uD83D\uDCC4 ${relPath}`);\n lines.push(`*${outline.language} | ${outline.lineCount} lines | ~${outline.estimatedTokens} tokens*\\n`);\n\n if (outline.symbols.length === 0) {\n lines.push('No symbols found (language may not be supported).');\n return lines.join('\\n');\n }\n\n const typeIcons: Record<string, string> = {\n class: '\uD83C\uDFDB\uFE0F', interface: '\uD83D\uDD37', type: '\uD83D\uDD39', enum: '\uD83D\uDCCB',\n function: '\u26A1', method: ' \u21B3', variable: '\uD83D\uDCCC', export: '\uD83D\uDCE4',\n };\n\n for (const sym of outline.symbols) {\n const icon = typeIcons[sym.type] || '\u2022';\n lines.push(`${icon} ${sym.signature} (L${sym.startLine}-${sym.endLine})`);\n }\n\n return lines.join('\\n');\n }\n\n // ============ Helpers ============\n\n /**\n * Find the end line of a code block (brace/indent matching)\n */\n private static findEndLine(lines: string[], startIdx: number, language: string): number {\n if (startIdx >= lines.length) return startIdx + 1;\n\n // For brace-based languages\n if (['typescript', 'javascript', 'php', 'go', 'rust', 'java', 'csharp', 'vue', 'svelte'].includes(language)) {\n let braceCount = 0;\n let foundOpen = false;\n\n for (let i = startIdx; i < lines.length; i++) {\n const line = lines[i];\n for (const ch of line) {\n if (ch === '{') { braceCount++; foundOpen = true; }\n if (ch === '}') braceCount--;\n }\n if (foundOpen && braceCount <= 0) return i + 1;\n }\n\n // Fallback: no braces found (declaration/one-liner)\n return startIdx + 1;\n }\n\n // For Python: indent-based\n if (language === 'python' || language === 'ruby') {\n const startIndent = lines[startIdx].search(/\\S/);\n for (let i = startIdx + 1; i < lines.length; i++) {\n const line = lines[i];\n if (line.trim() === '') continue; // Skip empty\n const indent = line.search(/\\S/);\n if (indent <= startIndent) return i;\n }\n return lines.length;\n }\n\n return startIdx + 1;\n }\n\n /**\n * Walk directory recursively, calling callback for each file\n */\n private static async walkDir(dirPath: string, callback: (filePath: string) => Promise<void>): Promise<void> {\n const entries = await fs.readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const full = path.join(dirPath, entry.name);\n\n // Skip common non-source directories\n if (entry.isDirectory()) {\n if (['node_modules', '.git', 'dist', 'build', '__pycache__', '.next', 'vendor', 'coverage'].includes(entry.name)) {\n continue;\n }\n await CodeParser.walkDir(full, callback);\n } else {\n await callback(full);\n }\n }\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAGA,SAAS,YAAY,UAAU;AAC/B,OAAO,UAAU;AAJjB,IAMa;AANb;AAAA;AAAA;AAMO,IAAM,kBAAN,MAAsB;AAAA,MAC3B,aAAa,gBAAgB,SAAgC;AAC3D,cAAM,GAAG,MAAM,SAAS,EAAE,WAAW,KAAK,CAAC;AAAA,MAC7C;AAAA,MAEA,aAAa,WAAW,UAAoC;AAC1D,YAAI;AACF,gBAAM,GAAG,OAAO,QAAQ;AACxB,iBAAO;AAAA,QACT,QAAQ;AACN,iBAAO;AAAA,QACT;AAAA,MACF;AAAA,MAEA,aAAa,SAAS,UAAmC;AACvD,eAAO,MAAM,GAAG,SAAS,UAAU,OAAO;AAAA,MAC5C;AAAA,MAEA,aAAa,UAAU,UAAkB,SAAgC;AACvE,cAAM,GAAG,UAAU,UAAU,SAAS,OAAO;AAAA,MAC/C;AAAA,MAEA,aAAa,cAAc,SAAoC;AAC7D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,IAAI,eAAe;AAC1C,UAAM,eAAe,QAAQ,QAAQ;AAAA,EACvC,SAAS,OAAO;AACd,YAAQ,MAAM,UAAW,MAAgB,OAAO,EAAE;AAClD,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;AAEH,WACG,QAAQ,uBAAuB,EAC/B,YAAY,wCAAwC,EACpD,OAAO,eAAe,eAAe,IAAI,EACzC,OAAO,OAAO,OAAe,YAAgC,YAAiB;AAC7E,MAAI;AACF,UAAM,iBAAiB,IAAI,eAAe;AAC1C,UAAM,eAAe,OAAO,OAAO,cAAc,KAAK,EAAE,OAAO,SAAS,QAAQ,KAAK,EAAE,CAAC;AAAA,EAC1F,SAAS,OAAO;AACd,YAAQ,MAAM,UAAW,MAAgB,OAAO,EAAE;AAClD,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;AAEH,WACG,QAAQ,wBAAwB,EAChC,YAAY,+CAA+C,EAC3D,OAAO,OAAO,UAAkB,eAAuB;AACtD,MAAI;AACF,UAAM,iBAAiB,IAAI,eAAe;AAC1C,UAAM,eAAe,OAAO,UAAU,UAAU;AAAA,EAClD,SAAS,OAAO;AACd,YAAQ,MAAM,UAAW,MAAgB,OAAO,EAAE;AAClD,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;AAEH,QAAQ,MAAM;",
6
+ "names": ["path", "fs", "path", "fs", "fs", "path", "path", "path", "path", "ora", "packageJsonPath", "require", "createRequire", "fileURLToPath", "dirname", "join", "ora", "chalk", "path", "fileURLToPath", "dirname", "join", "createRequire", "require", "__filename", "__dirname", "path", "ora", "chalk", "packageJsonPath", "SkillCommand", "path", "path", "ora", "chalk", "path", "ora", "chalk", "MemoryCommand", "memoryCmd", "path", "chalk", "ora", "createHash", "readFileSync", "path", "ora", "chalk", "createHash", "path", "ora", "chalk", "path", "chalk", "readFileSync", "path", "chalk", "path", "chalk", "readFileSync", "path", "createHash", "z", "z", "z", "readFileSync", "path", "createHash", "path", "chalk", "chalk", "path", "chalk", "ora", "fs", "path", "chalk", "ora", "fs", "path", "chalk", "ora", "ora", "path", "chalk", "fs", "path", "chalk", "ora", "fs", "chalk", "chalk", "ora", "path", "fs", "path", "ora", "path", "chalk", "outline", "require", "createRequire", "__filename", "fileURLToPath", "__dirname", "dirname", "join"]
7
7
  }