heraspec 0.1.14 → 0.1.16

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 (236) hide show
  1. package/LICENSE +187 -0
  2. package/README.md +140 -107
  3. package/bin/heraspec.js +1491 -155
  4. package/bin/heraspec.js.map +4 -4
  5. package/dist/cli/index.d.ts +2 -0
  6. package/dist/commands/audit.d.ts +37 -0
  7. package/dist/commands/create.d.ts +11 -0
  8. package/dist/commands/explore.d.ts +17 -0
  9. package/dist/commands/helper.d.ts +13 -0
  10. package/dist/commands/hotfix.d.ts +9 -0
  11. package/dist/commands/make-code.d.ts +14 -0
  12. package/dist/commands/make-docs.d.ts +36 -0
  13. package/dist/commands/make-test.d.ts +60 -0
  14. package/dist/commands/memory.d.ts +101 -0
  15. package/dist/commands/pack.d.ts +17 -0
  16. package/dist/commands/show.d.ts +8 -0
  17. package/dist/commands/skill.d.ts +8 -0
  18. package/dist/commands/suggest.d.ts +32 -0
  19. package/dist/commands/validate.d.ts +8 -0
  20. package/dist/core/archive.d.ts +14 -0
  21. package/dist/core/config.d.ts +33 -0
  22. package/dist/core/init.d.ts +97 -0
  23. package/dist/core/list.d.ts +7 -0
  24. package/dist/core/memory/config-advisor.d.ts +30 -0
  25. package/dist/core/memory/context-config.d.ts +14 -0
  26. package/dist/core/memory/context-generator.d.ts +19 -0
  27. package/dist/core/memory/index.d.ts +12 -0
  28. package/dist/core/memory/memory-schema.d.ts +34 -0
  29. package/dist/core/memory/memory-search.d.ts +45 -0
  30. package/dist/core/memory/memory-store.d.ts +71 -0
  31. package/dist/core/memory/memory-types.d.ts +159 -0
  32. package/dist/core/memory/memory-vector.d.ts +23 -0
  33. package/dist/core/parsers/code-parser.d.ts +53 -0
  34. package/dist/core/parsers/markdown-parser.d.ts +18 -0
  35. package/dist/core/restore.d.ts +9 -0
  36. package/dist/core/schemas/base.schema.d.ts +55 -0
  37. package/dist/core/schemas/change.schema.d.ts +35 -0
  38. package/dist/core/schemas/index.d.ts +7 -0
  39. package/dist/core/schemas/spec.schema.d.ts +50 -0
  40. package/dist/core/skills/index.d.ts +6 -0
  41. package/dist/core/skills/skill-manager.d.ts +28 -0
  42. package/dist/core/skills/skill-parser.d.ts +24 -0
  43. package/dist/core/sync.d.ts +6 -0
  44. package/dist/core/templates/index.d.ts +10 -0
  45. package/dist/core/templates/skills/README.md +44 -38
  46. package/dist/core/templates/skills/campaign-plan/skill.md +76 -0
  47. package/dist/core/templates/skills/campaign-plan/skill.vi.md +76 -0
  48. package/dist/core/templates/skills/campaign-plan-skill.md +76 -0
  49. package/dist/core/templates/skills/campaign-plan-skill.vi.md +76 -0
  50. package/dist/core/templates/skills/code-review/skill.md +70 -0
  51. package/dist/core/templates/skills/code-review/skill.vi.md +70 -0
  52. package/dist/core/templates/skills/code-review-skill.md +70 -0
  53. package/dist/core/templates/skills/code-review-skill.vi.md +70 -0
  54. package/dist/core/templates/skills/content-creation/skill.md +69 -0
  55. package/dist/core/templates/skills/content-creation/skill.vi.md +69 -0
  56. package/dist/core/templates/skills/content-creation-skill.md +69 -0
  57. package/dist/core/templates/skills/content-creation-skill.vi.md +69 -0
  58. package/dist/core/templates/skills/content-optimization/skill.md +104 -0
  59. package/dist/core/templates/skills/debug/skill.md +69 -0
  60. package/dist/core/templates/skills/debug/skill.vi.md +69 -0
  61. package/dist/core/templates/skills/debug-skill.md +69 -0
  62. package/dist/core/templates/skills/debug-skill.vi.md +69 -0
  63. package/dist/core/templates/skills/deploy-documentation/skill.md +408 -0
  64. package/dist/core/templates/skills/design-system/knowledge/design-systems/airbnb/DESIGN.md +246 -0
  65. package/dist/core/templates/skills/design-system/knowledge/design-systems/airtable/DESIGN.md +89 -0
  66. package/dist/core/templates/skills/design-system/knowledge/design-systems/apple/DESIGN.md +313 -0
  67. package/dist/core/templates/skills/design-system/knowledge/design-systems/bmw/DESIGN.md +180 -0
  68. package/dist/core/templates/skills/design-system/knowledge/design-systems/cal/DESIGN.md +259 -0
  69. package/dist/core/templates/skills/design-system/knowledge/design-systems/claude/DESIGN.md +312 -0
  70. package/dist/core/templates/skills/design-system/knowledge/design-systems/clay/DESIGN.md +304 -0
  71. package/dist/core/templates/skills/design-system/knowledge/design-systems/clickhouse/DESIGN.md +281 -0
  72. package/dist/core/templates/skills/design-system/knowledge/design-systems/cohere/DESIGN.md +266 -0
  73. package/dist/core/templates/skills/design-system/knowledge/design-systems/coinbase/DESIGN.md +129 -0
  74. package/dist/core/templates/skills/design-system/knowledge/design-systems/composio/DESIGN.md +307 -0
  75. package/dist/core/templates/skills/design-system/knowledge/design-systems/cursor/DESIGN.md +309 -0
  76. package/dist/core/templates/skills/design-system/knowledge/design-systems/elevenlabs/DESIGN.md +265 -0
  77. package/dist/core/templates/skills/design-system/knowledge/design-systems/expo/DESIGN.md +281 -0
  78. package/dist/core/templates/skills/design-system/knowledge/design-systems/figma/DESIGN.md +220 -0
  79. package/dist/core/templates/skills/design-system/knowledge/design-systems/framer/DESIGN.md +246 -0
  80. package/dist/core/templates/skills/design-system/knowledge/design-systems/hashicorp/DESIGN.md +278 -0
  81. package/dist/core/templates/skills/design-system/knowledge/design-systems/ibm/DESIGN.md +332 -0
  82. package/dist/core/templates/skills/design-system/knowledge/design-systems/index.json +72 -0
  83. package/dist/core/templates/skills/design-system/knowledge/design-systems/intercom/DESIGN.md +146 -0
  84. package/dist/core/templates/skills/design-system/knowledge/design-systems/kraken/DESIGN.md +125 -0
  85. package/dist/core/templates/skills/design-system/knowledge/design-systems/linear.app/DESIGN.md +367 -0
  86. package/dist/core/templates/skills/design-system/knowledge/design-systems/lovable/DESIGN.md +298 -0
  87. package/dist/core/templates/skills/design-system/knowledge/design-systems/minimax/DESIGN.md +257 -0
  88. package/dist/core/templates/skills/design-system/knowledge/design-systems/mintlify/DESIGN.md +326 -0
  89. package/dist/core/templates/skills/design-system/knowledge/design-systems/miro/DESIGN.md +108 -0
  90. package/dist/core/templates/skills/design-system/knowledge/design-systems/mistral.ai/DESIGN.md +261 -0
  91. package/dist/core/templates/skills/design-system/knowledge/design-systems/mongodb/DESIGN.md +266 -0
  92. package/dist/core/templates/skills/design-system/knowledge/design-systems/notion/DESIGN.md +309 -0
  93. package/dist/core/templates/skills/design-system/knowledge/design-systems/nvidia/DESIGN.md +293 -0
  94. package/dist/core/templates/skills/design-system/knowledge/design-systems/ollama/DESIGN.md +267 -0
  95. package/dist/core/templates/skills/design-system/knowledge/design-systems/opencode.ai/DESIGN.md +281 -0
  96. package/dist/core/templates/skills/design-system/knowledge/design-systems/pinterest/DESIGN.md +230 -0
  97. package/dist/core/templates/skills/design-system/knowledge/design-systems/posthog/DESIGN.md +256 -0
  98. package/dist/core/templates/skills/design-system/knowledge/design-systems/raycast/DESIGN.md +268 -0
  99. package/dist/core/templates/skills/design-system/knowledge/design-systems/replicate/DESIGN.md +261 -0
  100. package/dist/core/templates/skills/design-system/knowledge/design-systems/resend/DESIGN.md +303 -0
  101. package/dist/core/templates/skills/design-system/knowledge/design-systems/revolut/DESIGN.md +185 -0
  102. package/dist/core/templates/skills/design-system/knowledge/design-systems/runwayml/DESIGN.md +244 -0
  103. package/dist/core/templates/skills/design-system/knowledge/design-systems/sanity/DESIGN.md +357 -0
  104. package/dist/core/templates/skills/design-system/knowledge/design-systems/sentry/DESIGN.md +262 -0
  105. package/dist/core/templates/skills/design-system/knowledge/design-systems/spacex/DESIGN.md +194 -0
  106. package/dist/core/templates/skills/design-system/knowledge/design-systems/spotify/DESIGN.md +246 -0
  107. package/dist/core/templates/skills/design-system/knowledge/design-systems/stripe/DESIGN.md +322 -0
  108. package/dist/core/templates/skills/design-system/knowledge/design-systems/supabase/DESIGN.md +255 -0
  109. package/dist/core/templates/skills/design-system/knowledge/design-systems/superhuman/DESIGN.md +252 -0
  110. package/dist/core/templates/skills/design-system/knowledge/design-systems/together.ai/DESIGN.md +263 -0
  111. package/dist/core/templates/skills/design-system/knowledge/design-systems/uber/DESIGN.md +295 -0
  112. package/dist/core/templates/skills/design-system/knowledge/design-systems/vercel/DESIGN.md +310 -0
  113. package/dist/core/templates/skills/design-system/knowledge/design-systems/voltagent/DESIGN.md +323 -0
  114. package/dist/core/templates/skills/design-system/knowledge/design-systems/warp/DESIGN.md +253 -0
  115. package/dist/core/templates/skills/design-system/knowledge/design-systems/webflow/DESIGN.md +92 -0
  116. package/dist/core/templates/skills/design-system/knowledge/design-systems/wise/DESIGN.md +173 -0
  117. package/dist/core/templates/skills/design-system/knowledge/design-systems/x.ai/DESIGN.md +257 -0
  118. package/dist/core/templates/skills/design-system/knowledge/design-systems/zapier/DESIGN.md +328 -0
  119. package/dist/core/templates/skills/design-system/skill.md +176 -0
  120. package/dist/core/templates/skills/documents/skill.md +104 -0
  121. package/dist/core/templates/skills/e2e-test/skill.md +119 -0
  122. package/dist/core/templates/skills/email-sequence/skill.md +68 -0
  123. package/dist/core/templates/skills/email-sequence/skill.vi.md +68 -0
  124. package/dist/core/templates/skills/email-sequence-skill.md +68 -0
  125. package/dist/core/templates/skills/email-sequence-skill.vi.md +68 -0
  126. package/dist/core/templates/skills/git-embed/skill.md +57 -0
  127. package/dist/core/templates/skills/integration-test/skill.md +118 -0
  128. package/dist/core/templates/skills/knowledge/README.md +63 -63
  129. package/dist/core/templates/skills/knowledge/design-systems/index.json +72 -72
  130. package/dist/core/templates/skills/knowledge/frameworks/php/codeigniter/rise-cms/profile.json +27 -27
  131. package/dist/core/templates/skills/knowledge/frameworks/php/codeigniter/rise-cms/structure.md +137 -137
  132. package/dist/core/templates/skills/knowledge/frameworks/php/laravel/botble/profile.json +39 -39
  133. package/dist/core/templates/skills/knowledge/frameworks/php/laravel/botble/structure.md +207 -207
  134. package/dist/core/templates/skills/knowledge/frameworks/php/wordpress/core/profile.json +51 -51
  135. package/dist/core/templates/skills/knowledge/frameworks/php/wordpress/core/structure.md +369 -369
  136. package/dist/core/templates/skills/knowledge/index.json +65 -65
  137. package/dist/core/templates/skills/perfex-module/code-quality-guidelines/skill.md +130 -0
  138. package/dist/core/templates/skills/perfex-module/envato-review-guidelines/skill.md +132 -0
  139. package/dist/core/templates/skills/perfex-module/module-codebase/scripts/scaffold-module.js +151 -0
  140. package/dist/core/templates/skills/perfex-module/module-codebase/skill.md +204 -0
  141. package/dist/core/templates/skills/perfex-module/module-codebase/templates/Test_Module.php +79 -0
  142. package/dist/core/templates/skills/perfex-module/module-codebase/templates/controller-admin.php +71 -0
  143. package/dist/core/templates/skills/perfex-module/module-codebase/templates/controller-api.php +58 -0
  144. package/dist/core/templates/skills/perfex-module/module-codebase/templates/deploy.ps1 +97 -0
  145. package/dist/core/templates/skills/perfex-module/module-codebase/templates/helper.php +97 -0
  146. package/dist/core/templates/skills/perfex-module/module-codebase/templates/install.php +30 -0
  147. package/dist/core/templates/skills/perfex-module/module-codebase/templates/model-main.php +94 -0
  148. package/dist/core/templates/skills/perfex-module/module-codebase/templates/module-main.php +91 -0
  149. package/dist/core/templates/skills/perfex-module/module-codebase/templates/package.json +30 -0
  150. package/dist/core/templates/skills/perfex-module/module-codebase/templates/uninstall.php +11 -0
  151. package/dist/core/templates/skills/perfex-module/module-codebase/templates/webpack.config.js +163 -0
  152. package/dist/core/templates/skills/perfex-module/skill.md +50 -0
  153. package/dist/core/templates/skills/project-memory/skill.md +222 -0
  154. package/dist/core/templates/skills/project-memory/skill.vi.md +223 -0
  155. package/dist/core/templates/skills/seo-audit/skill.md +75 -0
  156. package/dist/core/templates/skills/seo-audit/skill.vi.md +75 -0
  157. package/dist/core/templates/skills/seo-audit-skill.md +75 -0
  158. package/dist/core/templates/skills/seo-audit-skill.vi.md +75 -0
  159. package/dist/core/templates/skills/smart-explore/skill.md +141 -0
  160. package/dist/core/templates/skills/sourcecode-analyzer/skill.md +210 -0
  161. package/dist/core/templates/skills/sourcecode-analyzer/skill.vi.md +210 -0
  162. package/dist/core/templates/skills/spec-writer/skill.md +61 -0
  163. package/dist/core/templates/skills/spec-writer/skill.vi.md +61 -0
  164. package/dist/core/templates/skills/spec-writer-skill.md +61 -0
  165. package/dist/core/templates/skills/spec-writer-skill.vi.md +61 -0
  166. package/dist/core/templates/skills/sql-queries/skill.md +67 -0
  167. package/dist/core/templates/skills/sql-queries/skill.vi.md +67 -0
  168. package/dist/core/templates/skills/sql-queries-skill.md +67 -0
  169. package/dist/core/templates/skills/sql-queries-skill.vi.md +67 -0
  170. package/dist/core/templates/skills/suggestion/skill.md +118 -0
  171. package/dist/core/templates/skills/system-design/skill.md +70 -0
  172. package/dist/core/templates/skills/system-design/skill.vi.md +70 -0
  173. package/dist/core/templates/skills/system-design-skill.md +70 -0
  174. package/dist/core/templates/skills/system-design-skill.vi.md +70 -0
  175. package/dist/core/templates/skills/tech-debt/skill.md +70 -0
  176. package/dist/core/templates/skills/tech-debt/skill.vi.md +70 -0
  177. package/dist/core/templates/skills/tech-debt-skill.md +70 -0
  178. package/dist/core/templates/skills/tech-debt-skill.vi.md +70 -0
  179. package/dist/core/templates/skills/ui-ux/data/charts.csv +26 -0
  180. package/dist/core/templates/skills/ui-ux/data/colors.csv +97 -0
  181. package/dist/core/templates/skills/ui-ux/data/design-systems.csv +54 -0
  182. package/dist/core/templates/skills/ui-ux/data/landing.csv +31 -0
  183. package/dist/core/templates/skills/ui-ux/data/pages-proposed.csv +22 -0
  184. package/dist/core/templates/skills/ui-ux/data/pages.csv +10 -0
  185. package/dist/core/templates/skills/ui-ux/data/products.csv +97 -0
  186. package/dist/core/templates/skills/ui-ux/data/prompts.csv +24 -0
  187. package/dist/core/templates/skills/ui-ux/data/stacks/flutter.csv +53 -0
  188. package/dist/core/templates/skills/ui-ux/data/stacks/html-tailwind.csv +56 -0
  189. package/dist/core/templates/skills/ui-ux/data/stacks/nextjs.csv +53 -0
  190. package/dist/core/templates/skills/ui-ux/data/stacks/react-native.csv +52 -0
  191. package/dist/core/templates/skills/ui-ux/data/stacks/react.csv +54 -0
  192. package/dist/core/templates/skills/ui-ux/data/stacks/svelte.csv +54 -0
  193. package/dist/core/templates/skills/ui-ux/data/stacks/swiftui.csv +51 -0
  194. package/dist/core/templates/skills/ui-ux/data/stacks/vue.csv +50 -0
  195. package/dist/core/templates/skills/ui-ux/data/styles.csv +59 -0
  196. package/dist/core/templates/skills/ui-ux/data/typography.csv +58 -0
  197. package/dist/core/templates/skills/ui-ux/data/ux-guidelines.csv +100 -0
  198. package/dist/core/templates/skills/ui-ux/scripts/CODE_EXPLANATION.md +394 -0
  199. package/dist/core/templates/skills/ui-ux/scripts/SEARCH_ALGORITHMS_COMPARISON.md +421 -0
  200. package/dist/core/templates/skills/ui-ux/scripts/SEARCH_MODES_GUIDE.md +238 -0
  201. package/dist/core/templates/skills/ui-ux/scripts/core.py +391 -0
  202. package/dist/core/templates/skills/ui-ux/scripts/search.py +73 -0
  203. package/dist/core/templates/skills/ui-ux/skill.md +595 -0
  204. package/dist/core/templates/skills/ui-ux/templates/accessibility-checklist.md +40 -0
  205. package/dist/core/templates/skills/ui-ux/templates/example-prompt-full-theme.md +333 -0
  206. package/dist/core/templates/skills/ui-ux/templates/page-types-guide.md +338 -0
  207. package/dist/core/templates/skills/ui-ux/templates/pages-proposed-summary.md +273 -0
  208. package/dist/core/templates/skills/ui-ux/templates/pre-delivery-checklist.md +42 -0
  209. package/dist/core/templates/skills/ui-ux/templates/prompt-template-full-theme.md +313 -0
  210. package/dist/core/templates/skills/ui-ux/templates/responsive-design.md +40 -0
  211. package/dist/core/templates/skills/unit-test/skill.md +111 -0
  212. package/dist/core/templates/skills/wordpress/plugin-check/skill.md +151 -0
  213. package/dist/core/templates/skills/wordpress/plugin-directory/skill.md +396 -0
  214. package/dist/core/templates/skills/wordpress/plugin-standard/skill.md +100 -0
  215. package/dist/core/templates/skills/wordpress/plugin-standard/templates/admin-dashboard.php +47 -0
  216. package/dist/core/templates/skills/wordpress/plugin-standard/templates/admin-settings.php +60 -0
  217. package/dist/core/templates/skills/wordpress/plugin-standard/templates/assets/admin-css.css +22 -0
  218. package/dist/core/templates/skills/wordpress/plugin-standard/templates/assets/admin-js.js +15 -0
  219. package/dist/core/templates/skills/wordpress/plugin-standard/templates/plugin-main.php +169 -0
  220. package/dist/core/templates/skills/wordpress/plugin-standard/templates/readme.txt +41 -0
  221. package/dist/core/templates/skills/wordpress/plugin-standard/templates/uninstall.php +21 -0
  222. package/dist/core/templates/skills/wordpress/ux-element/skill.md +83 -0
  223. package/dist/core/templates/skills/wordpress/ux-element/templates/Controller.php +50 -0
  224. package/dist/core/templates/skills/wordpress/ux-element/templates/Shortcode.php +23 -0
  225. package/dist/core/templates/skills/wordpress/ux-element/templates/Template.html +20 -0
  226. package/dist/core/templates/skills/wordpress/ux-element/templates/Thumbnail.svg +8 -0
  227. package/dist/core/templates/skills/wordpress/ux-element/templates/View.php +21 -0
  228. package/dist/core/templates/skills-template-map.d.ts +29 -0
  229. package/dist/core/validation/validator.d.ts +26 -0
  230. package/dist/core/view.d.ts +4 -0
  231. package/dist/index.d.ts +11 -0
  232. package/dist/index.js +350 -114
  233. package/dist/utils/file-system.d.ts +19 -0
  234. package/dist/utils/index.d.ts +6 -0
  235. package/dist/utils/task-parser.d.ts +26 -0
  236. package/package.json +2 -2
package/bin/heraspec.js CHANGED
@@ -214,95 +214,168 @@ var init_skills_template_map = __esm({
214
214
  SKILL_TEMPLATE_MAP = {
215
215
  // Cross-cutting skills
216
216
  "ui-ux": {
217
- templateFileName: "ui-ux-skill.md",
217
+ templateFileName: "ui-ux/skill.md",
218
218
  isCrossCutting: true,
219
- resourceDirs: ["scripts", "templates", "data"]
219
+ resourceDirs: ["ui-ux/scripts", "ui-ux/templates", "ui-ux/data"]
220
220
  },
221
221
  "design-system": {
222
- templateFileName: "design-system-skill.md",
222
+ templateFileName: "design-system/skill.md",
223
223
  isCrossCutting: true,
224
- resourceDirs: ["scripts", "data", "knowledge/design-systems"]
224
+ resourceDirs: ["ui-ux/scripts", "ui-ux/data", "design-system/knowledge/design-systems"]
225
225
  },
226
226
  "documents": {
227
- templateFileName: "documents-skill.md",
227
+ templateFileName: "documents/skill.md",
228
228
  isCrossCutting: true,
229
229
  resourceDirs: ["documents/templates"]
230
230
  },
231
231
  "content-optimization": {
232
- templateFileName: "content-optimization-skill.md",
232
+ templateFileName: "content-optimization/skill.md",
233
233
  isCrossCutting: true
234
234
  },
235
235
  "unit-test": {
236
- templateFileName: "unit-test-skill.md",
236
+ templateFileName: "unit-test/skill.md",
237
237
  isCrossCutting: true
238
238
  },
239
239
  "integration-test": {
240
- templateFileName: "integration-test-skill.md",
240
+ templateFileName: "integration-test/skill.md",
241
241
  isCrossCutting: true
242
242
  },
243
243
  "e2e-test": {
244
- templateFileName: "e2e-test-skill.md",
244
+ templateFileName: "e2e-test/skill.md",
245
245
  isCrossCutting: true
246
246
  },
247
247
  "suggestion": {
248
- templateFileName: "suggestion-skill.md",
248
+ templateFileName: "suggestion/skill.md",
249
249
  isCrossCutting: true
250
250
  },
251
251
  "sourcecode-analyzer": {
252
- templateFileName: "sourcecode-analyzer-skill.md",
252
+ templateFileName: "sourcecode-analyzer/skill.md",
253
253
  isCrossCutting: true,
254
- viFileName: "sourcecode-analyzer-skill.vi.md"
254
+ viFileName: "sourcecode-analyzer/skill.vi.md"
255
255
  },
256
256
  "project-memory": {
257
- templateFileName: "project-memory-skill.md",
258
- viFileName: "project-memory-skill.vi.md",
257
+ templateFileName: "project-memory/skill.md",
258
+ viFileName: "project-memory/skill.vi.md",
259
259
  isCrossCutting: true
260
260
  },
261
261
  "smart-explore": {
262
- templateFileName: "smart-explore-skill.md",
262
+ templateFileName: "smart-explore/skill.md",
263
263
  isCrossCutting: true
264
264
  },
265
265
  "deploy-documentation": {
266
- templateFileName: "deploy-documentation-skill.md",
266
+ templateFileName: "deploy-documentation/skill.md",
267
267
  isCrossCutting: true,
268
- resourceDirs: ["templates"]
268
+ resourceDirs: ["ui-ux/templates"]
269
+ },
270
+ "code-review": {
271
+ templateFileName: "code-review/skill.md",
272
+ viFileName: "code-review/skill.vi.md",
273
+ isCrossCutting: true
274
+ },
275
+ "debug": {
276
+ templateFileName: "debug/skill.md",
277
+ viFileName: "debug/skill.vi.md",
278
+ isCrossCutting: true
279
+ },
280
+ "system-design": {
281
+ templateFileName: "system-design/skill.md",
282
+ viFileName: "system-design/skill.vi.md",
283
+ isCrossCutting: true
284
+ },
285
+ "tech-debt": {
286
+ templateFileName: "tech-debt/skill.md",
287
+ viFileName: "tech-debt/skill.vi.md",
288
+ isCrossCutting: true
289
+ },
290
+ "spec-writer": {
291
+ templateFileName: "spec-writer/skill.md",
292
+ viFileName: "spec-writer/skill.vi.md",
293
+ isCrossCutting: true
294
+ },
295
+ "seo-audit": {
296
+ templateFileName: "seo-audit/skill.md",
297
+ viFileName: "seo-audit/skill.vi.md",
298
+ isCrossCutting: true
299
+ },
300
+ "campaign-plan": {
301
+ templateFileName: "campaign-plan/skill.md",
302
+ viFileName: "campaign-plan/skill.vi.md",
303
+ isCrossCutting: true
304
+ },
305
+ "content-creation": {
306
+ templateFileName: "content-creation/skill.md",
307
+ viFileName: "content-creation/skill.vi.md",
308
+ isCrossCutting: true
309
+ },
310
+ "email-sequence": {
311
+ templateFileName: "email-sequence/skill.md",
312
+ viFileName: "email-sequence/skill.vi.md",
313
+ isCrossCutting: true
314
+ },
315
+ "sql-queries": {
316
+ templateFileName: "sql-queries/skill.md",
317
+ viFileName: "sql-queries/skill.vi.md",
318
+ isCrossCutting: true
269
319
  },
270
320
  // Perfex module skills
321
+ "perfex-module": {
322
+ templateFileName: "perfex-module/skill.md",
323
+ isCrossCutting: true,
324
+ resourceDirs: [
325
+ "perfex-module/module-codebase",
326
+ "perfex-module/code-quality-guidelines",
327
+ "perfex-module/envato-review-guidelines"
328
+ ]
329
+ },
271
330
  "perfex-module:module-codebase": {
272
- templateFileName: "module-codebase-skill.md",
331
+ templateFileName: "perfex-module/module-codebase/skill.md",
332
+ isCrossCutting: false,
333
+ projectType: "perfex-module",
334
+ resourceDirs: [
335
+ "perfex-module/module-codebase/templates",
336
+ "perfex-module/module-codebase/scripts"
337
+ ]
338
+ },
339
+ "perfex-module:code-quality-guidelines": {
340
+ templateFileName: "perfex-module/code-quality-guidelines/skill.md",
341
+ isCrossCutting: false,
342
+ projectType: "perfex-module"
343
+ },
344
+ "perfex-module:envato-review-guidelines": {
345
+ templateFileName: "perfex-module/envato-review-guidelines/skill.md",
273
346
  isCrossCutting: false,
274
347
  projectType: "perfex-module"
275
348
  },
276
349
  "wordpress:ux-element": {
277
- templateFileName: "ux-element-skill.md",
350
+ templateFileName: "wordpress/ux-element/skill.md",
278
351
  isCrossCutting: false,
279
352
  projectType: "wordpress",
280
- resourceDirs: ["ux-element/templates"]
353
+ resourceDirs: ["wordpress/ux-element/templates"]
281
354
  },
282
355
  "wordpress:plugin-standard": {
283
- templateFileName: "wordpress-plugin-standard-skill.md",
356
+ templateFileName: "wordpress/plugin-standard/skill.md",
284
357
  isCrossCutting: false,
285
358
  projectType: "wordpress",
286
- resourceDirs: ["wordpress-plugin-standard/templates"]
359
+ resourceDirs: ["wordpress/plugin-standard/templates"]
287
360
  },
288
361
  "wordpress:plugin-check": {
289
- templateFileName: "wordpress-plugin-check-skill.md",
362
+ templateFileName: "wordpress/plugin-check/skill.md",
290
363
  isCrossCutting: false,
291
364
  projectType: "wordpress"
292
365
  },
293
366
  "wordpress:plugin-directory": {
294
- templateFileName: "plugin-directory-skill.md",
367
+ templateFileName: "wordpress/plugin-directory/skill.md",
295
368
  isCrossCutting: false,
296
369
  projectType: "wordpress"
297
370
  },
298
371
  // WordPress Plugin specific (matches PROJECT_TYPES)
299
372
  "wordpress-plugin:plugin-check": {
300
- templateFileName: "wordpress-plugin-check-skill.md",
373
+ templateFileName: "wordpress/plugin-check/skill.md",
301
374
  isCrossCutting: false,
302
375
  projectType: "wordpress-plugin"
303
376
  },
304
377
  "wordpress-plugin:plugin-directory": {
305
- templateFileName: "plugin-directory-skill.md",
378
+ templateFileName: "wordpress/plugin-directory/skill.md",
306
379
  isCrossCutting: false,
307
380
  projectType: "wordpress-plugin"
308
381
  }
@@ -541,9 +614,9 @@ var init_memory_store = __esm({
541
614
  );
542
615
  }
543
616
  const dir = path2.dirname(this.dbPath);
544
- const fs3 = __require("fs");
545
- if (!fs3.existsSync(dir)) {
546
- fs3.mkdirSync(dir, { recursive: true });
617
+ const fs5 = __require("fs");
618
+ if (!fs5.existsSync(dir)) {
619
+ fs5.mkdirSync(dir, { recursive: true });
547
620
  }
548
621
  this.db = new Database(this.dbPath);
549
622
  if (needsMigration(this.db)) {
@@ -566,12 +639,12 @@ var init_memory_store = __esm({
566
639
  logDbSizeChange() {
567
640
  try {
568
641
  const project = this.detectProjectName();
569
- const fs3 = __require("fs");
570
- if (fs3.existsSync(this.dbPath)) {
571
- let totalSize = fs3.statSync(this.dbPath).size;
642
+ const fs5 = __require("fs");
643
+ if (fs5.existsSync(this.dbPath)) {
644
+ let totalSize = fs5.statSync(this.dbPath).size;
572
645
  const walPath = this.dbPath + "-wal";
573
- if (fs3.existsSync(walPath)) {
574
- totalSize += fs3.statSync(walPath).size;
646
+ if (fs5.existsSync(walPath)) {
647
+ totalSize += fs5.statSync(walPath).size;
575
648
  }
576
649
  const now = /* @__PURE__ */ new Date();
577
650
  this.db.prepare(`
@@ -770,8 +843,8 @@ var init_memory_store = __esm({
770
843
  }
771
844
  let dbSizeBytes = 0;
772
845
  try {
773
- const fs3 = __require("fs");
774
- const stats = fs3.statSync(this.dbPath);
846
+ const fs5 = __require("fs");
847
+ const stats = fs5.statSync(this.dbPath);
775
848
  dbSizeBytes = stats.size;
776
849
  } catch {
777
850
  }
@@ -840,12 +913,12 @@ var init_memory_store = __esm({
840
913
  let savingsPercent = tokensWithoutMemory > 0 ? savingsTokens / tokensWithoutMemory * 100 : 0;
841
914
  let dbSizeBytes = 0;
842
915
  try {
843
- const fs3 = __require("fs");
844
- if (fs3.existsSync(this.dbPath)) {
845
- dbSizeBytes = fs3.statSync(this.dbPath).size;
916
+ const fs5 = __require("fs");
917
+ if (fs5.existsSync(this.dbPath)) {
918
+ dbSizeBytes = fs5.statSync(this.dbPath).size;
846
919
  const walPath = this.dbPath + "-wal";
847
- if (fs3.existsSync(walPath)) {
848
- dbSizeBytes += fs3.statSync(walPath).size;
920
+ if (fs5.existsSync(walPath)) {
921
+ dbSizeBytes += fs5.statSync(walPath).size;
849
922
  }
850
923
  }
851
924
  } catch {
@@ -931,10 +1004,10 @@ var init_memory_store = __esm({
931
1004
  }
932
1005
  detectProjectName() {
933
1006
  try {
934
- const fs3 = __require("fs");
1007
+ const fs5 = __require("fs");
935
1008
  const pkgPath = path2.join(process.cwd(), "package.json");
936
- if (fs3.existsSync(pkgPath)) {
937
- const pkg = JSON.parse(fs3.readFileSync(pkgPath, "utf-8"));
1009
+ if (fs5.existsSync(pkgPath)) {
1010
+ const pkg = JSON.parse(fs5.readFileSync(pkgPath, "utf-8"));
938
1011
  return pkg.name || path2.basename(process.cwd());
939
1012
  }
940
1013
  } catch {
@@ -1347,11 +1420,11 @@ import path3 from "path";
1347
1420
  function loadContextConfig(projectPath = ".") {
1348
1421
  const configPath = path3.join(projectPath, HERASPEC_DIR_NAME, MEMORY_DIR_NAME, CONFIG_FILENAME);
1349
1422
  try {
1350
- const fs3 = __require("fs");
1351
- if (!fs3.existsSync(configPath)) {
1423
+ const fs5 = __require("fs");
1424
+ if (!fs5.existsSync(configPath)) {
1352
1425
  return { ...DEFAULT_CONTEXT_CONFIG };
1353
1426
  }
1354
- const raw = JSON.parse(fs3.readFileSync(configPath, "utf-8"));
1427
+ const raw = JSON.parse(fs5.readFileSync(configPath, "utf-8"));
1355
1428
  return mergeConfig(raw);
1356
1429
  } catch {
1357
1430
  return { ...DEFAULT_CONTEXT_CONFIG };
@@ -1360,9 +1433,9 @@ function loadContextConfig(projectPath = ".") {
1360
1433
  function saveContextConfig(config, projectPath = ".") {
1361
1434
  const configDir = path3.join(projectPath, HERASPEC_DIR_NAME, MEMORY_DIR_NAME);
1362
1435
  const configPath = path3.join(configDir, CONFIG_FILENAME);
1363
- const fs3 = __require("fs");
1364
- if (!fs3.existsSync(configDir)) {
1365
- fs3.mkdirSync(configDir, { recursive: true });
1436
+ const fs5 = __require("fs");
1437
+ if (!fs5.existsSync(configDir)) {
1438
+ fs5.mkdirSync(configDir, { recursive: true });
1366
1439
  }
1367
1440
  const serializable = {
1368
1441
  totalObservationCount: config.totalObservationCount,
@@ -1373,7 +1446,7 @@ function saveContextConfig(config, projectPath = ".") {
1373
1446
  maxTokens: config.maxTokens,
1374
1447
  showLastSummary: config.showLastSummary
1375
1448
  };
1376
- fs3.writeFileSync(configPath, JSON.stringify(serializable, null, 2), "utf-8");
1449
+ fs5.writeFileSync(configPath, JSON.stringify(serializable, null, 2), "utf-8");
1377
1450
  }
1378
1451
  function mergeConfig(raw) {
1379
1452
  const defaults = DEFAULT_CONTEXT_CONFIG;
@@ -1458,12 +1531,12 @@ var init_context_generator = __esm({
1458
1531
  writeContextFile(projectPath = ".") {
1459
1532
  const context = this.generateContext(projectPath);
1460
1533
  const contextPath = __require("path").join(projectPath, "heraspec", "memory", "context.md");
1461
- const fs3 = __require("fs");
1534
+ const fs5 = __require("fs");
1462
1535
  const dir = __require("path").dirname(contextPath);
1463
- if (!fs3.existsSync(dir)) {
1464
- fs3.mkdirSync(dir, { recursive: true });
1536
+ if (!fs5.existsSync(dir)) {
1537
+ fs5.mkdirSync(dir, { recursive: true });
1465
1538
  }
1466
- fs3.writeFileSync(contextPath, context, "utf-8");
1539
+ fs5.writeFileSync(contextPath, context, "utf-8");
1467
1540
  return contextPath;
1468
1541
  }
1469
1542
  // ============ Private ============
@@ -2513,8 +2586,12 @@ var init_skill_parser = __esm({
2513
2586
  const sectionName = line.replace(/^##+\s+/, "").toLowerCase();
2514
2587
  currentSection = sectionName;
2515
2588
  if (sectionName.includes("m\u1EE5c \u0111\xEDch") || sectionName.includes("purpose")) {
2516
- if (i + 1 < lines.length && lines[i + 1].trim()) {
2517
- skill.purpose = lines[i + 1].trim();
2589
+ for (let j = i + 1; j < lines.length && !lines[j].startsWith("##"); j++) {
2590
+ const nextLine = lines[j].trim();
2591
+ if (nextLine) {
2592
+ skill.purpose = nextLine;
2593
+ break;
2594
+ }
2518
2595
  }
2519
2596
  }
2520
2597
  continue;
@@ -2621,7 +2698,7 @@ var init_skill_manager = __esm({
2621
2698
  projectType,
2622
2699
  skillName
2623
2700
  );
2624
- if (await FileSystemUtils.fileExists(path6.join(projectSkillPath, "skill.md"))) {
2701
+ if (await FileSystemUtils.fileExists(path6.join(projectSkillPath, "skill.md")) || await FileSystemUtils.fileExists(path6.join(projectSkillPath, "SKILL.md"))) {
2625
2702
  return projectSkillPath;
2626
2703
  }
2627
2704
  const crossCuttingPath = path6.join(
@@ -2630,7 +2707,7 @@ var init_skill_manager = __esm({
2630
2707
  SKILLS_DIR_NAME,
2631
2708
  skillName
2632
2709
  );
2633
- if (await FileSystemUtils.fileExists(path6.join(crossCuttingPath, "skill.md"))) {
2710
+ if (await FileSystemUtils.fileExists(path6.join(crossCuttingPath, "skill.md")) || await FileSystemUtils.fileExists(path6.join(crossCuttingPath, "SKILL.md"))) {
2634
2711
  return crossCuttingPath;
2635
2712
  }
2636
2713
  return null;
@@ -2668,9 +2745,15 @@ var init_skill_manager = __esm({
2668
2745
  if (isProjectType) {
2669
2746
  const projectSkills = await this.listSkillsInDirectory(entryPath, entry);
2670
2747
  skills.push(...projectSkills);
2748
+ if (await FileSystemUtils.fileExists(path6.join(entryPath, "skill.md")) || await FileSystemUtils.fileExists(path6.join(entryPath, "SKILL.md"))) {
2749
+ skills.push({
2750
+ projectType: entry,
2751
+ skillName: entry,
2752
+ path: entryPath
2753
+ });
2754
+ }
2671
2755
  } else {
2672
- const skillMdPath = path6.join(entryPath, "skill.md");
2673
- if (await FileSystemUtils.fileExists(skillMdPath)) {
2756
+ if (await FileSystemUtils.fileExists(path6.join(entryPath, "skill.md")) || await FileSystemUtils.fileExists(path6.join(entryPath, "SKILL.md"))) {
2674
2757
  skills.push({
2675
2758
  skillName: entry,
2676
2759
  path: entryPath
@@ -2707,8 +2790,7 @@ var init_skill_manager = __esm({
2707
2790
  const entryPath = path6.join(dir, entry);
2708
2791
  const stats = await FileSystemUtils.stat(entryPath);
2709
2792
  if (stats.isDirectory()) {
2710
- const skillMdPath = path6.join(entryPath, "skill.md");
2711
- if (await FileSystemUtils.fileExists(skillMdPath)) {
2793
+ if (await FileSystemUtils.fileExists(path6.join(entryPath, "skill.md")) || await FileSystemUtils.fileExists(path6.join(entryPath, "SKILL.md"))) {
2712
2794
  skills.push({
2713
2795
  projectType,
2714
2796
  skillName: entry,
@@ -3041,17 +3123,7 @@ var init_skill = __esm({
3041
3123
  }
3042
3124
  const isUpdate = await FileSystemUtils.fileExists(destPath);
3043
3125
  if (isUpdate) {
3044
- spinner.info(`Skill "${skillName}" already exists at ${destPath}`);
3045
- spinner.start(`Removing old version to update with latest...`);
3046
- try {
3047
- await FileSystemUtils.removeDirectory(destPath, true);
3048
- spinner.succeed(`Removed old skill "${skillName}"`);
3049
- } catch (error) {
3050
- spinner.fail(`Failed to remove old skill: ${error instanceof Error ? error.message : "Unknown error"}`);
3051
- process.exitCode = 1;
3052
- return;
3053
- }
3054
- spinner.start(`Adding updated skill "${skillName}"...`);
3126
+ spinner.info(`Skill "${skillName}" already exists at ${destPath} - updating template files (custom files preserved)...`);
3055
3127
  }
3056
3128
  await FileSystemUtils.createDirectory(destPath);
3057
3129
  const coreTemplatesDir = await getCoreTemplatesDir();
@@ -3067,6 +3139,10 @@ var init_skill = __esm({
3067
3139
  return;
3068
3140
  }
3069
3141
  await FileSystemUtils.copyFile(templateFile, path7.join(destPath, "skill.md"));
3142
+ const upperTemplateFile = path7.join(path7.dirname(templateFile), "SKILL.md");
3143
+ if (await FileSystemUtils.fileExists(upperTemplateFile)) {
3144
+ await FileSystemUtils.copyFile(upperTemplateFile, path7.join(destPath, "SKILL.md"));
3145
+ }
3070
3146
  if (templateInfo.viFileName) {
3071
3147
  const viFile = path7.join(coreTemplatesDir, templateInfo.viFileName);
3072
3148
  if (await FileSystemUtils.fileExists(viFile)) {
@@ -3076,7 +3152,7 @@ var init_skill = __esm({
3076
3152
  if (templateInfo.resourceDirs) {
3077
3153
  for (const resourceDir of templateInfo.resourceDirs) {
3078
3154
  const srcResourceDir = path7.join(coreTemplatesDir, resourceDir);
3079
- const destResourceDir = path7.join(destPath, resourceDir);
3155
+ const destResourceDir = path7.join(destPath, path7.basename(resourceDir));
3080
3156
  if (await FileSystemUtils.fileExists(srcResourceDir)) {
3081
3157
  await FileSystemUtils.copyDirectory(srcResourceDir, destResourceDir);
3082
3158
  }
@@ -3162,6 +3238,7 @@ This document defines the workflow for AI agents working with HeraSpec.
3162
3238
  - **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:
3163
3239
  - **Preferred**: Proactively install it via \`heraspec skill add <name>\` (e.g., \`heraspec skill add documents\`) if you have terminal access.
3164
3240
  - **Fallback**: If you cannot install it, **STOP** and ask the user to add it. **DO NOT** attempt manual generation without the skill.
3241
+ - **IGNORE VIETNAMESE SKILL FILES**: When reading and executing skill workflows, you **MUST ONLY** look at the English version of the skill instructions (e.g., \`skill.md\`). You **MUST completely ignore** all Vietnamese versions (e.g., \`skill.vi.md\` or files ending with \`*.vi.md\`). These Vietnamese files are for reference/development purposes by the user only.
3165
3242
  - **USER CONFIRMATION**: For destructive actions or public releases, always request explicit User approval first.
3166
3243
 
3167
3244
  ### Restricted Commands (REQUIRE USER CONFIRMATION)
@@ -3252,6 +3329,7 @@ The following commands are classified by risk level. You **MUST NOT** execute th
3252
3329
  - Understand purpose, steps, inputs, outputs
3253
3330
  - Follow tone, rules, and limitations
3254
3331
  - Check available templates and scripts
3332
+ - **Ignore Vietnamese Skill Files**: Only read the English \`skill.md\` instructions. Completely ignore any \`*.vi.md\` translation files.
3255
3333
 
3256
3334
  4. **Use skill resources**:
3257
3335
  - Run scripts from \`scripts/\` folder if needed
@@ -3328,6 +3406,24 @@ The following commands are classified by risk level. You **MUST NOT** execute th
3328
3406
  - **CRITICAL**: Agent MUST present full report and **wait for user confirmation** before making changes
3329
3407
  - Reference guideline numbers (e.g., "Guideline 7: User Tracking Consent")
3330
3408
 
3409
+ **Special case - Perfex Module Engineering skills:**
3410
+ - Tasks: \`(projectType: perfex-module, skill: module-codebase)\` or \`(projectType: perfex-module, skill: code-quality-guidelines)\` or \`(skill: perfex-module)\`
3411
+ - Install: \`heraspec skill add perfex-module\` or \`heraspec skill add module-codebase --project-type perfex-module\` or \`heraspec skill add code-quality-guidelines --project-type perfex-module\`
3412
+ - Agent reads: \`heraspec/skills/perfex-module/skill.md\`, \`heraspec/skills/perfex-module/module-codebase/skill.md\`, and \`heraspec/skills/perfex-module/code-quality-guidelines/skill.md\`
3413
+ - Agent MUST adhere to **10 Enterprise Code Quality & Clean Code Standards**:
3414
+ 1. **Separation of Concerns (Zero Inline Code)**: 0 inline <script> or <style> blocks in views and documentation HTML.
3415
+ 2. **Static Analysis Neutrality**: 0 occurrences of high-risk scanner triggers (inject, seeder, bypass, eval, unserialize).
3416
+ 3. **Safe Stylesheet Loading**: Use editor.dom.loadCSS() for TinyMCE/iframes; never inject raw CSS string arrays.
3417
+ 4. **Scoped Admin JS**: Enclose scripts in window.addEventListener('load') + strict IIFE.
3418
+ 5. **Concurrency & Performance**: Always call session_write_close() at the start of read/search AJAX endpoints.
3419
+ 6. **Clean Release Packaging**: Exclude package.json, webpack.config.js, tests/, scratch/, .git in deploy.ps1.
3420
+ 7. **Defensive PHP Security & Guards**: 100% PHP files start with defined('BASEPATH') or exit('No direct script access allowed');. Use CI Query Builder with auto-escaping.
3421
+ 8. **DOM XSS Prevention (CWE-79)**: Use .textContent, .innerText, or strict HTML escaping helper; purify rich text.
3422
+ 9. **100% Multilingual Parity**: 100% labels and messages use _l('key') with zero missing keys across languages.
3423
+ 10. **Zero Emojis**: 0 Unicode emojis across custom code, comments, views, documentation, and UI.
3424
+ - Use templates from \`heraspec/skills/perfex-module/module-codebase/templates/\` (module-main.php, install.php, uninstall.php, controller-admin.php, controller-api.php, model-main.php, helper.php, deploy.ps1, webpack.config.js).
3425
+
3426
+
3331
3427
 
3332
3428
  - Follow tasks.md
3333
3429
  - Mark tasks completed: \`- [x]\`
@@ -3458,6 +3554,7 @@ If \\\`heraspec/skills/smart-explore/\\\` exists, prefer token-efficient explora
3458
3554
  > heraspec skill add documents"
3459
3555
  - **DO NOT** create a task plan or attempt manual generation without the skill language.
3460
3556
  3. **Execute After Install**: Only after the skill folder is created (or installed), read the \`skill.md\` and proceed with the task.
3557
+ 4. **Ignore Vietnamese Skill Files**: You MUST only read the English \`skill.md\` file inside the skill folder. Completely ignore all \`*.vi.md\` files (e.g., \`skill.vi.md\`), as they are strictly for reference purposes by human developers.
3461
3558
 
3462
3559
  **Example prompt for Documents skill:**
3463
3560
  If you need to generate multi-format documentation, use this prompt:
@@ -3824,20 +3921,86 @@ ${section.content.trimEnd()}`);
3824
3921
  }
3825
3922
  }
3826
3923
  /**
3827
- * Generic section replacer: replace content from marker to next ## header
3924
+ * Find the index of the next top-level H2 section in the markdown content.
3925
+ * Tracks fenced code blocks to ignore H2 headers inside code blocks.
3926
+ */
3927
+ findSectionEndIndex(content, startIndex) {
3928
+ const lines = content.substring(startIndex).split(/\r?\n/);
3929
+ let offset = startIndex;
3930
+ let inCodeBlock = false;
3931
+ for (let i = 0; i < lines.length; i++) {
3932
+ const line = lines[i];
3933
+ const lineLengthWithNewline = line.length + (content.charAt(offset + line.length) === "\r" ? 2 : 1);
3934
+ if (i === 0) {
3935
+ offset += lineLengthWithNewline;
3936
+ continue;
3937
+ }
3938
+ if (line.trim().startsWith("```")) {
3939
+ inCodeBlock = !inCodeBlock;
3940
+ }
3941
+ if (!inCodeBlock && line.startsWith("## ")) {
3942
+ return offset;
3943
+ }
3944
+ offset += lineLengthWithNewline;
3945
+ }
3946
+ return content.length;
3947
+ }
3948
+ /**
3949
+ * Finds the start index of the next standard section in the sequence.
3950
+ * This is used to replace the entire section cleanly, even if there are internal H2s or duplicates.
3951
+ */
3952
+ findNextSectionIndex(content, startIndex, currentHeader) {
3953
+ const sectionsOrder = [
3954
+ ["## Universal Safety Rules"],
3955
+ ["## Core Workflow"],
3956
+ ["## Skills System", "## Skills system", "### Skills System", "### skills system"],
3957
+ ["## Proactive Memory-Aware Development", "## Memory-Aware Development"]
3958
+ ];
3959
+ let currentGroupIndex = -1;
3960
+ for (let i = 0; i < sectionsOrder.length; i++) {
3961
+ if (sectionsOrder[i].some((h) => currentHeader.toLowerCase().trim() === h.toLowerCase().trim())) {
3962
+ currentGroupIndex = i;
3963
+ break;
3964
+ }
3965
+ }
3966
+ if (currentGroupIndex === -1) {
3967
+ return this.findSectionEndIndex(content, startIndex);
3968
+ }
3969
+ let nextSectionIndex = -1;
3970
+ for (let i = currentGroupIndex + 1; i < sectionsOrder.length; i++) {
3971
+ const variations = sectionsOrder[i];
3972
+ for (const variation of variations) {
3973
+ const idx = content.indexOf(variation, startIndex + currentHeader.length);
3974
+ if (idx !== -1) {
3975
+ if (nextSectionIndex === -1 || idx < nextSectionIndex) {
3976
+ nextSectionIndex = idx;
3977
+ }
3978
+ }
3979
+ }
3980
+ }
3981
+ if (nextSectionIndex !== -1) {
3982
+ return nextSectionIndex;
3983
+ }
3984
+ return this.findSectionEndIndex(content, startIndex);
3985
+ }
3986
+ /**
3987
+ * Generic section replacer: replace content from marker to next H2 header or endMarker
3828
3988
  */
3829
- replaceSection(content, sectionMarker, newSection) {
3989
+ replaceSection(content, sectionMarker, newSection, endMarker) {
3830
3990
  const startIndex = content.indexOf(sectionMarker);
3831
3991
  if (startIndex === -1) return content;
3832
- let endIndex = content.indexOf("\n## ", startIndex + sectionMarker.length);
3992
+ let endIndex = -1;
3993
+ if (endMarker) {
3994
+ endIndex = content.indexOf(endMarker, startIndex + sectionMarker.length);
3995
+ }
3833
3996
  if (endIndex === -1) {
3834
- endIndex = content.length;
3997
+ endIndex = this.findNextSectionIndex(content, startIndex, sectionMarker);
3835
3998
  }
3836
3999
  const before = content.substring(0, startIndex).trimEnd();
3837
4000
  const after = content.substring(endIndex);
3838
4001
  return before + "\n\n" + newSection + (after.trimStart().startsWith("\n") ? "" : "\n\n") + after;
3839
4002
  }
3840
- replaceSkillsSection(existingContent, newSkillsSection) {
4003
+ replaceSkillsSection(existingContent, newSkillsSection, endMarker) {
3841
4004
  const startMarkers = ["## Skills System", "## Skills system", "### Skills System", "### Skills system"];
3842
4005
  let startIndex = -1;
3843
4006
  let foundMarker = "";
@@ -3851,28 +4014,19 @@ ${section.content.trimEnd()}`);
3851
4014
  if (startIndex === -1) {
3852
4015
  return this.appendSkillsSection(existingContent, newSkillsSection);
3853
4016
  }
3854
- let endIndex = existingContent.indexOf("\n## ", startIndex + foundMarker.length);
3855
- if (endIndex === -1) {
3856
- endIndex = existingContent.indexOf("\n### ", startIndex + foundMarker.length);
4017
+ let endIndex = -1;
4018
+ if (endMarker) {
4019
+ endIndex = existingContent.indexOf(endMarker, startIndex + foundMarker.length);
3857
4020
  }
3858
4021
  if (endIndex === -1) {
3859
- endIndex = existingContent.length;
4022
+ endIndex = this.findNextSectionIndex(existingContent, startIndex, foundMarker);
3860
4023
  }
3861
4024
  const before = existingContent.substring(0, startIndex).trimEnd();
3862
4025
  const after = existingContent.substring(endIndex);
3863
4026
  return before + "\n\n" + newSkillsSection + (after.trimStart().startsWith("\n") ? "" : "\n\n") + after;
3864
4027
  }
3865
4028
  replaceSafetyRules(existingContent, newSafetySection) {
3866
- const marker = "## Universal Safety Rules";
3867
- const startIndex = existingContent.indexOf(marker);
3868
- if (startIndex === -1) return existingContent;
3869
- let endIndex = existingContent.indexOf("\n## ", startIndex + marker.length);
3870
- if (endIndex === -1) {
3871
- endIndex = existingContent.length;
3872
- }
3873
- const before = existingContent.substring(0, startIndex).trimEnd();
3874
- const after = existingContent.substring(endIndex);
3875
- return before + "\n\n" + newSafetySection + (after.trimStart().startsWith("\n") ? "" : "\n\n") + after;
4029
+ return this.replaceSection(existingContent, "## Universal Safety Rules", newSafetySection, "## Core Workflow");
3876
4030
  }
3877
4031
  appendSkillsSection(existingContent, skillsSection) {
3878
4032
  const rulesMarker = "\n## Rules\n";
@@ -3927,36 +4081,78 @@ ${section.content.trimEnd()}`);
3927
4081
  }
3928
4082
  return null;
3929
4083
  }
4084
+ /**
4085
+ * Refactor legacy installed skills if new standards or companion skills were added to HeraSpec.
4086
+ * Ensures backward compatibility and non-destructive enhancement for existing projects.
4087
+ */
4088
+ async refactorLegacySkills(skillsDir, coreTemplatesDir) {
4089
+ const perfexSkillDir = path8.join(skillsDir, "perfex-module");
4090
+ if (await FileSystemUtils.fileExists(perfexSkillDir)) {
4091
+ const rootSkillMd = path8.join(perfexSkillDir, "skill.md");
4092
+ const rootSkillUpperMd = path8.join(perfexSkillDir, "SKILL.md");
4093
+ const templateRootSkill = path8.join(coreTemplatesDir, "perfex-module", "skill.md");
4094
+ const templateRootUpper = path8.join(coreTemplatesDir, "perfex-module", "SKILL.md");
4095
+ if (!await FileSystemUtils.fileExists(rootSkillMd) && await FileSystemUtils.fileExists(templateRootSkill)) {
4096
+ await FileSystemUtils.copyFile(templateRootSkill, rootSkillMd);
4097
+ }
4098
+ if (!await FileSystemUtils.fileExists(rootSkillUpperMd) && await FileSystemUtils.fileExists(templateRootUpper)) {
4099
+ await FileSystemUtils.copyFile(templateRootUpper, rootSkillUpperMd);
4100
+ }
4101
+ const qualityGuidelinesDir = path8.join(perfexSkillDir, "code-quality-guidelines");
4102
+ const templateQualityDir = path8.join(coreTemplatesDir, "perfex-module", "code-quality-guidelines");
4103
+ if (!await FileSystemUtils.fileExists(qualityGuidelinesDir) && await FileSystemUtils.fileExists(templateQualityDir)) {
4104
+ console.log(chalk2.cyan(" \u2713 Refactored perfex-module: added code-quality-guidelines skill"));
4105
+ await FileSystemUtils.copyDirectory(templateQualityDir, qualityGuidelinesDir);
4106
+ }
4107
+ const codebaseDir = path8.join(perfexSkillDir, "module-codebase");
4108
+ const templateCodebaseDir = path8.join(coreTemplatesDir, "perfex-module", "module-codebase");
4109
+ if (await FileSystemUtils.fileExists(codebaseDir) && await FileSystemUtils.fileExists(templateCodebaseDir)) {
4110
+ await FileSystemUtils.copyDirectory(templateCodebaseDir, codebaseDir);
4111
+ }
4112
+ }
4113
+ }
3930
4114
  /**
3931
4115
  * Update installed built-in skills on re-init.
3932
4116
  *
3933
4117
  * Rules:
3934
4118
  * - Only update skills that exist in SKILL_TEMPLATE_MAP (built-in / known skills)
3935
4119
  * - Skip skills NOT in the template map (custom skills added by the project)
4120
+ * - Strictly preserve custom project skills: NEVER delete or overwrite them
3936
4121
  * - For each matching skill: update skill.md + re-copy resourceDirs from template
3937
- * but PRESERVE templates/, scripts/, examples/ sub-folders added by user
4122
+ * safely preserving any user files in templates/, scripts/, examples/ sub-folders
3938
4123
  */
3939
4124
  async updateInstalledSkills(heraspecPath) {
3940
4125
  const skillsDir = path8.join(heraspecPath, SKILLS_DIR_NAME);
3941
4126
  if (!await FileSystemUtils.fileExists(skillsDir)) return;
3942
4127
  const coreTemplatesDir = await this.getCoreTemplatesDir();
3943
4128
  if (!coreTemplatesDir) return;
4129
+ await this.refactorLegacySkills(skillsDir, coreTemplatesDir);
3944
4130
  const allTemplates = getAllSkillTemplates();
3945
4131
  let updatedCount = 0;
3946
- let skippedCount = 0;
4132
+ const preservedSkills = [];
3947
4133
  const installedSkillPaths = await this.collectInstalledSkillPaths(skillsDir);
3948
4134
  for (const { skillPath, skillName, projectType } of installedSkillPaths) {
3949
4135
  const templateInfo = getSkillTemplateInfo(skillName, projectType);
3950
4136
  if (!templateInfo) {
3951
- skippedCount++;
4137
+ const displayName = projectType ? `${projectType}/${skillName}` : skillName;
4138
+ if (!preservedSkills.includes(displayName)) {
4139
+ preservedSkills.push(displayName);
4140
+ }
3952
4141
  continue;
3953
4142
  }
3954
4143
  const templateFile = path8.join(coreTemplatesDir, templateInfo.templateFileName);
3955
4144
  if (!await FileSystemUtils.fileExists(templateFile)) {
3956
- skippedCount++;
4145
+ const displayName = projectType ? `${projectType}/${skillName}` : skillName;
4146
+ if (!preservedSkills.includes(displayName)) {
4147
+ preservedSkills.push(displayName);
4148
+ }
3957
4149
  continue;
3958
4150
  }
3959
4151
  await FileSystemUtils.copyFile(templateFile, path8.join(skillPath, "skill.md"));
4152
+ const upperTemplateFile = path8.join(path8.dirname(templateFile), "SKILL.md");
4153
+ if (await FileSystemUtils.fileExists(upperTemplateFile)) {
4154
+ await FileSystemUtils.copyFile(upperTemplateFile, path8.join(skillPath, "SKILL.md"));
4155
+ }
3960
4156
  if (templateInfo.viFileName) {
3961
4157
  const viFile = path8.join(coreTemplatesDir, templateInfo.viFileName);
3962
4158
  if (await FileSystemUtils.fileExists(viFile)) {
@@ -3966,11 +4162,8 @@ ${section.content.trimEnd()}`);
3966
4162
  if (templateInfo.resourceDirs) {
3967
4163
  for (const resourceDir of templateInfo.resourceDirs) {
3968
4164
  const srcResourceDir = path8.join(coreTemplatesDir, resourceDir);
3969
- const destResourceDir = path8.join(skillPath, resourceDir);
4165
+ const destResourceDir = path8.join(skillPath, path8.basename(resourceDir));
3970
4166
  if (await FileSystemUtils.fileExists(srcResourceDir)) {
3971
- if (await FileSystemUtils.fileExists(destResourceDir)) {
3972
- await FileSystemUtils.removeDirectory(destResourceDir, true);
3973
- }
3974
4167
  await FileSystemUtils.copyDirectory(srcResourceDir, destResourceDir);
3975
4168
  }
3976
4169
  }
@@ -3981,7 +4174,13 @@ ${section.content.trimEnd()}`);
3981
4174
  updatedCount++;
3982
4175
  }
3983
4176
  if (updatedCount > 0) {
3984
- console.log(chalk2.gray(` \u2713 Updated ${updatedCount} built-in skill(s)${skippedCount > 0 ? `, skipped ${skippedCount} custom skill(s)` : ""}`));
4177
+ console.log(chalk2.gray(` \u2713 Updated ${updatedCount} built-in skill(s)`));
4178
+ }
4179
+ if (preservedSkills.length > 0) {
4180
+ console.log(chalk2.green(` \u2713 Preserved ${preservedSkills.length} custom project skill(s) (never deleted or overwritten):`));
4181
+ for (const skill of preservedSkills) {
4182
+ console.log(chalk2.gray(` \u2022 ${skill}`));
4183
+ }
3985
4184
  }
3986
4185
  }
3987
4186
  /**
@@ -4003,20 +4202,25 @@ ${section.content.trimEnd()}`);
4003
4202
  "multi-stack"
4004
4203
  ];
4005
4204
  for (const entry of entries) {
4205
+ if (entry === "README.md" || entry === "UI_UX_SKILL_QUICK_REFERENCE.md") continue;
4006
4206
  const entryPath = path8.join(skillsDir, entry);
4007
4207
  const stats = await FileSystemUtils.stat(entryPath);
4008
4208
  if (!stats.isDirectory()) continue;
4009
4209
  if (knownProjectTypes.includes(entry)) {
4010
4210
  const subEntries = await FileSystemUtils.readDirectory(entryPath);
4011
4211
  for (const sub of subEntries) {
4212
+ if (["templates", "scripts", "examples", "data", "knowledge", "tests", "docs"].includes(sub)) continue;
4012
4213
  const subPath = path8.join(entryPath, sub);
4013
4214
  const subStats = await FileSystemUtils.stat(subPath);
4014
- if (subStats.isDirectory() && await FileSystemUtils.fileExists(path8.join(subPath, "skill.md"))) {
4215
+ if (subStats.isDirectory()) {
4015
4216
  result.push({ skillPath: subPath, skillName: sub, projectType: entry });
4016
4217
  }
4017
4218
  }
4219
+ if (await FileSystemUtils.fileExists(path8.join(entryPath, "skill.md")) || await FileSystemUtils.fileExists(path8.join(entryPath, "SKILL.md"))) {
4220
+ result.push({ skillPath: entryPath, skillName: entry, projectType: entry });
4221
+ }
4018
4222
  } else {
4019
- if (await FileSystemUtils.fileExists(path8.join(entryPath, "skill.md"))) {
4223
+ if (await FileSystemUtils.fileExists(path8.join(entryPath, "skill.md")) || await FileSystemUtils.fileExists(path8.join(entryPath, "SKILL.md"))) {
4020
4224
  result.push({ skillPath: entryPath, skillName: entry });
4021
4225
  }
4022
4226
  }
@@ -4267,15 +4471,12 @@ python3 heraspec/skills/ui-ux/scripts/search.py "pricing plans" --domain pages
4267
4471
  1. Copy skill from HeraSpec core:
4268
4472
  \`\`\`bash
4269
4473
  # Copy UI/UX skill
4270
- cp -r /path/to/HeraSpec/src/core/templates/skills/ui-ux-skill.md heraspec/skills/ui-ux/
4271
- cp -r /path/to/HeraSpec/src/core/templates/skills/scripts heraspec/skills/ui-ux/
4272
- cp -r /path/to/HeraSpec/src/core/templates/skills/data heraspec/skills/ui-ux/
4273
- cp -r /path/to/HeraSpec/src/core/templates/skills/templates heraspec/skills/ui-ux/
4474
+ cp -r /path/to/HeraSpec/src/core/templates/skills/ui-ux heraspec/skills/
4274
4475
  \`\`\`
4275
4476
 
4276
4477
  2. Or use \`heraspec skill add ui-ux\` (if available)
4277
4478
 
4278
- 3. Read \`heraspec/skills/ui-ux/ui-ux-skill.md\` for complete documentation
4479
+ 3. Read \`heraspec/skills/ui-ux/skill.md\` for complete documentation
4279
4480
 
4280
4481
  ### Flatsome UX Element Skill
4281
4482
 
@@ -4425,7 +4626,7 @@ python3 heraspec/skills/ui-ux/scripts/search.py "product-detail single-product"
4425
4626
  ## \u{1F4DA} Detailed Documentation
4426
4627
 
4427
4628
  After copying UI/UX skill to your project, see:
4428
- - \`heraspec/skills/ui-ux/ui-ux-skill.md\` - Complete skill documentation
4629
+ - \`heraspec/skills/ui-ux/skill.md\` - Complete skill documentation
4429
4630
  - \`heraspec/skills/ui-ux/templates/example-prompt-full-theme.md\` - Detailed prompt examples
4430
4631
  - \`heraspec/skills/ui-ux/templates/prompt-template-full-theme.md\` - Copy-paste templates
4431
4632
 
@@ -4441,10 +4642,7 @@ After copying UI/UX skill to your project, see:
4441
4642
 
4442
4643
  1. Copy UI/UX skill to project:
4443
4644
  \`\`\`bash
4444
- cp -r /path/to/HeraSpec/src/core/templates/skills/ui-ux-skill.md heraspec/skills/ui-ux/
4445
- cp -r /path/to/HeraSpec/src/core/templates/skills/scripts heraspec/skills/ui-ux/
4446
- cp -r /path/to/HeraSpec/src/core/templates/skills/data heraspec/skills/ui-ux/
4447
- cp -r /path/to/HeraSpec/src/core/templates/skills/templates heraspec/skills/ui-ux/
4645
+ cp -r /path/to/HeraSpec/src/core/templates/skills/ui-ux heraspec/skills/
4448
4646
  \`\`\`
4449
4647
 
4450
4648
  2. Use prompt template from above
@@ -4471,32 +4669,45 @@ After copying UI/UX skill to your project, see:
4471
4669
  async updateReadmeFile(readmePath) {
4472
4670
  const existingContent = await FileSystemUtils.readFile(readmePath);
4473
4671
  const heraspecSection = this.getHeraSpecReadmeSection();
4474
- const sectionMarkers = [
4475
- "## HeraSpec",
4476
- "## HeraSpec Development",
4477
- "### HeraSpec",
4478
- "### HeraSpec Development",
4479
- "<!-- HeraSpec Section -->"
4480
- ];
4481
- let hasHeraSpecSection = false;
4482
4672
  let sectionStartIndex = -1;
4483
4673
  let sectionEndIndex = -1;
4484
- for (const marker of sectionMarkers) {
4485
- const index = existingContent.indexOf(marker);
4486
- if (index !== -1) {
4487
- hasHeraSpecSection = true;
4488
- sectionStartIndex = index;
4489
- sectionEndIndex = existingContent.indexOf("\n## ", index + marker.length);
4490
- if (sectionEndIndex === -1) {
4491
- sectionEndIndex = existingContent.indexOf("\n### ", index + marker.length);
4492
- }
4493
- if (sectionEndIndex === -1) {
4494
- sectionEndIndex = existingContent.length;
4674
+ const commentMarker = "<!-- HeraSpec Section -->";
4675
+ const commentIndex = existingContent.indexOf(commentMarker);
4676
+ if (commentIndex !== -1) {
4677
+ sectionStartIndex = commentIndex;
4678
+ const firstHeaderIndex = existingContent.indexOf("## ", commentIndex + commentMarker.length);
4679
+ if (firstHeaderIndex !== -1) {
4680
+ let nextHeaderIndex = existingContent.indexOf("\n## ", firstHeaderIndex + 3);
4681
+ if (nextHeaderIndex === -1) {
4682
+ nextHeaderIndex = existingContent.indexOf("\n### ", firstHeaderIndex + 3);
4683
+ }
4684
+ sectionEndIndex = nextHeaderIndex !== -1 ? nextHeaderIndex : existingContent.length;
4685
+ } else {
4686
+ sectionEndIndex = existingContent.length;
4687
+ }
4688
+ } else {
4689
+ const sectionMarkers = [
4690
+ "## HeraSpec Development",
4691
+ "## HeraSpec",
4692
+ "### HeraSpec Development",
4693
+ "### HeraSpec"
4694
+ ];
4695
+ for (const marker of sectionMarkers) {
4696
+ const index = existingContent.indexOf(marker);
4697
+ if (index !== -1) {
4698
+ sectionStartIndex = index;
4699
+ sectionEndIndex = existingContent.indexOf("\n## ", index + marker.length);
4700
+ if (sectionEndIndex === -1) {
4701
+ sectionEndIndex = existingContent.indexOf("\n### ", index + marker.length);
4702
+ }
4703
+ if (sectionEndIndex === -1) {
4704
+ sectionEndIndex = existingContent.length;
4705
+ }
4706
+ break;
4495
4707
  }
4496
- break;
4497
4708
  }
4498
4709
  }
4499
- if (hasHeraSpecSection && sectionStartIndex !== -1) {
4710
+ if (sectionStartIndex !== -1) {
4500
4711
  const before = existingContent.substring(0, sectionStartIndex).trimEnd();
4501
4712
  const after = existingContent.substring(sectionEndIndex);
4502
4713
  const updatedContent = before + "\n\n" + heraspecSection + (after.trimStart().startsWith("\n") ? "" : "\n\n") + after;
@@ -4876,7 +5087,6 @@ This will archive "${changeName}" and merge delta specs into source specs.`);
4876
5087
  const archiveDir = path10.join(
4877
5088
  ".",
4878
5089
  HERASPEC_DIR_NAME,
4879
- CHANGES_DIR_NAME,
4880
5090
  ARCHIVES_DIR_NAME
4881
5091
  );
4882
5092
  await FileSystemUtils.createDirectory(archiveDir);
@@ -5200,7 +5410,6 @@ var RestoreCommand = class {
5200
5410
  const archivesDir = path12.join(
5201
5411
  ".",
5202
5412
  HERASPEC_DIR_NAME,
5203
- CHANGES_DIR_NAME,
5204
5413
  ARCHIVES_DIR_NAME
5205
5414
  );
5206
5415
  if (!await FileSystemUtils.fileExists(archivesDir)) {
@@ -5638,19 +5847,31 @@ var Validator = class {
5638
5847
  const spec = parser.parseSpec(specName);
5639
5848
  const result = SpecSchema.safeParse(spec);
5640
5849
  if (!result.success) {
5641
- result.error.errors.forEach((err) => {
5642
- errors.push(`${err.path.join(".")}: ${err.message}`);
5850
+ result.error.issues.forEach((err) => {
5851
+ errors.push({
5852
+ message: `${err.path.join(".")}: ${err.message}`,
5853
+ autoFixable: false
5854
+ });
5643
5855
  });
5644
5856
  }
5645
5857
  if (spec.requirements.length === 0) {
5646
- errors.push("Spec must have at least one requirement");
5858
+ errors.push({
5859
+ message: "Spec must have at least one requirement",
5860
+ autoFixable: false
5861
+ });
5647
5862
  }
5648
5863
  for (const req of spec.requirements) {
5649
5864
  if (!req.description || req.description.trim().length === 0) {
5650
- errors.push(`Requirement "${req.name}" must have a description`);
5865
+ errors.push({
5866
+ message: `Requirement "${req.name}" must have a description`,
5867
+ autoFixable: false
5868
+ });
5651
5869
  }
5652
5870
  if (!req.scenarios || req.scenarios.length === 0) {
5653
- warnings.push(`Requirement "${req.name}" has no scenarios`);
5871
+ warnings.push({
5872
+ message: `Requirement "${req.name}" has no scenarios`,
5873
+ autoFixable: false
5874
+ });
5654
5875
  }
5655
5876
  }
5656
5877
  return {
@@ -5661,7 +5882,10 @@ var Validator = class {
5661
5882
  } catch (error) {
5662
5883
  return {
5663
5884
  valid: false,
5664
- errors: [error instanceof Error ? error.message : "Unknown error"],
5885
+ errors: [{
5886
+ message: error instanceof Error ? error.message : "Unknown error",
5887
+ autoFixable: false
5888
+ }],
5665
5889
  warnings: []
5666
5890
  };
5667
5891
  }
@@ -5828,6 +6052,15 @@ var Validator = class {
5828
6052
  const match = content.match(reqRegex);
5829
6053
  return match ? match[0].trim() : null;
5830
6054
  }
6055
+ getParseErrorSuggestion(errorMessage) {
6056
+ if (errorMessage.includes("YAML") || errorMessage.includes("frontmatter")) {
6057
+ return "Check the YAML frontmatter syntax at the top of the file.";
6058
+ }
6059
+ if (errorMessage.includes("header") || errorMessage.includes("heading")) {
6060
+ return "Ensure headers follow markdown format (# Title, ## Section).";
6061
+ }
6062
+ return void 0;
6063
+ }
5831
6064
  };
5832
6065
 
5833
6066
  // src/commands/validate.ts
@@ -5958,7 +6191,13 @@ var HelperCommand = class {
5958
6191
  { cmd: "heraspec archive [name]", desc: "Archive completed change" },
5959
6192
  { cmd: "heraspec restore [name]", desc: "Restore change from archive" },
5960
6193
  { cmd: "heraspec skill list", desc: "List available skills" },
5961
- { cmd: "heraspec skill show <name>", desc: "Show skill details" },
6194
+ { cmd: "heraspec create <name>", desc: "Scaffold new module/plugin with clean architecture" },
6195
+ { cmd: "heraspec audit [path]", desc: "Audit code quality, security & clean standards" },
6196
+ { cmd: "heraspec audit --fix", desc: "Auto-fix safe code quality issues (e.g. PHP guards)" },
6197
+ { cmd: "heraspec pack [path]", desc: "Build and package production .zip release" },
6198
+ { cmd: "heraspec memory context", desc: "Generate token-efficient agent context markdown" },
6199
+ { cmd: "heraspec memory query <query>", desc: "Semantic search project memory" },
6200
+ { cmd: "heraspec explore outline <file>", desc: "Show structural skeleton of a file" },
5962
6201
  { cmd: "heraspec make docs", desc: "Generate product documentation" },
5963
6202
  { cmd: "heraspec make docs --agent <name>", desc: "Generate docs with AI agent" },
5964
6203
  { cmd: "heraspec make test", desc: "Generate test cases from specs" },
@@ -5968,7 +6207,7 @@ var HelperCommand = class {
5968
6207
  { cmd: "heraspec helper", desc: "Show this guide" }
5969
6208
  ];
5970
6209
  commands.forEach(({ cmd, desc }) => {
5971
- console.log(chalk8.cyan(` ${cmd.padEnd(35)}`) + chalk8.white(desc));
6210
+ console.log(chalk8.cyan(` ${cmd.padEnd(38)}`) + chalk8.white(desc));
5972
6211
  });
5973
6212
  console.log("\n" + "\u2500".repeat(70) + "\n");
5974
6213
  }
@@ -6116,7 +6355,11 @@ var HelperCommand = class {
6116
6355
  "Validate with suggestions: heraspec validate <name> (includes fix suggestions)",
6117
6356
  "Get feature suggestions: heraspec suggest (analyzes project and suggests enhancements)",
6118
6357
  "Use test skills: unit-test, integration-test, e2e-test for test implementation",
6119
- 'Plugin Check: Use "skill plugin-check" to ensure code quality and safety'
6358
+ 'Plugin Check: Use "skill plugin-check" to ensure code quality and safety',
6359
+ "Quality & Security Audit: heraspec audit (checks 7 clean architecture and OWASP rules)",
6360
+ "Auto-fix Audit Issues: heraspec audit --fix (safely adds missing direct access guards)",
6361
+ "Production Packaging: heraspec pack (auto-builds assets & strips dev bloat into release .zip)",
6362
+ "Scaffold Clean Architecture: heraspec create <name> --type perfex-module|wordpress-plugin"
6120
6363
  ];
6121
6364
  tips.forEach((tip) => {
6122
6365
  console.log(chalk8.white(` \u2022 ${tip}`));
@@ -6226,8 +6469,8 @@ Found ${specFiles.length} feature(s)`));
6226
6469
  * Recursively find spec files
6227
6470
  */
6228
6471
  async findSpecFilesRecursive(dir, files) {
6229
- const fs3 = await import("fs/promises");
6230
- const entries = await fs3.readdir(dir, { withFileTypes: true });
6472
+ const fs5 = await import("fs/promises");
6473
+ const entries = await fs5.readdir(dir, { withFileTypes: true });
6231
6474
  for (const entry of entries) {
6232
6475
  const entryPath = path16.join(dir, entry.name);
6233
6476
  if (entry.isDirectory()) {
@@ -6490,8 +6733,8 @@ Test type: ${testType}`));
6490
6733
  * Recursively find spec files
6491
6734
  */
6492
6735
  async findSpecFilesRecursive(dir, files) {
6493
- const fs3 = await import("fs/promises");
6494
- const entries = await fs3.readdir(dir, { withFileTypes: true });
6736
+ const fs5 = await import("fs/promises");
6737
+ const entries = await fs5.readdir(dir, { withFileTypes: true });
6495
6738
  for (const entry of entries) {
6496
6739
  const entryPath = path17.join(dir, entry.name);
6497
6740
  if (entry.isDirectory()) {
@@ -6750,8 +6993,8 @@ Specs analyzed: ${specFiles.length}`));
6750
6993
  return specFiles.sort();
6751
6994
  }
6752
6995
  async findSpecFilesRecursive(dir, files) {
6753
- const fs3 = await import("fs/promises");
6754
- const entries = await fs3.readdir(dir, { withFileTypes: true });
6996
+ const fs5 = await import("fs/promises");
6997
+ const entries = await fs5.readdir(dir, { withFileTypes: true });
6755
6998
  for (const entry of entries) {
6756
6999
  const entryPath = path18.join(dir, entry.name);
6757
7000
  if (entry.isDirectory()) {
@@ -6971,8 +7214,8 @@ Found ${specs.length} existing feature(s)`));
6971
7214
  * Recursively find spec files
6972
7215
  */
6973
7216
  async findSpecFilesRecursive(dir, files) {
6974
- const fs3 = await import("fs/promises");
6975
- const entries = await fs3.readdir(dir, { withFileTypes: true });
7217
+ const fs5 = await import("fs/promises");
7218
+ const entries = await fs5.readdir(dir, { withFileTypes: true });
6976
7219
  for (const entry of entries) {
6977
7220
  const entryPath = path19.join(dir, entry.name);
6978
7221
  if (entry.isDirectory()) {
@@ -7536,6 +7779,1072 @@ Symbol "${symbolName}" not found in ${filePath}`));
7536
7779
  }
7537
7780
  };
7538
7781
 
7782
+ // src/commands/audit.ts
7783
+ init_file_system();
7784
+ init_config();
7785
+ import path22 from "path";
7786
+ import { promises as fs3 } from "fs";
7787
+ import chalk15 from "chalk";
7788
+ import ora12 from "ora";
7789
+ var AuditCommand = class {
7790
+ issues = [];
7791
+ passedCount = 0;
7792
+ async execute(targetPath = ".", options) {
7793
+ const startTime = Date.now();
7794
+ const spinner = ora12("Auditing codebase for quality, security & clean standards...").start();
7795
+ try {
7796
+ const resolvedPath = path22.resolve(targetPath);
7797
+ if (!await FileSystemUtils.fileExists(resolvedPath)) {
7798
+ spinner.fail(`Directory not found: ${resolvedPath}`);
7799
+ process.exitCode = 1;
7800
+ return;
7801
+ }
7802
+ const projectType = options?.type || await this.detectProjectType(resolvedPath);
7803
+ spinner.text = `Auditing ${chalk15.cyan(projectType)} codebase at: ${resolvedPath}`;
7804
+ this.issues = [];
7805
+ this.passedCount = 0;
7806
+ const allFiles = await this.collectFiles(resolvedPath);
7807
+ await this.auditPhpGuards(allFiles, projectType, options?.fix);
7808
+ await this.auditZeroInlineCode(allFiles);
7809
+ await this.auditTriggerWords(allFiles);
7810
+ if (projectType.includes("perfex") || projectType.includes("backend")) {
7811
+ await this.auditSessionConcurrency(allFiles);
7812
+ }
7813
+ await this.auditLanguageParity(resolvedPath);
7814
+ await this.auditEmojis(allFiles);
7815
+ await this.auditPackagingRules(resolvedPath);
7816
+ const durationMs = Date.now() - startTime;
7817
+ spinner.stop();
7818
+ const report = {
7819
+ passed: this.passedCount,
7820
+ warnings: this.issues.filter((i) => i.type === "warning").length,
7821
+ errors: this.issues.filter((i) => i.type === "error").length,
7822
+ issues: this.issues,
7823
+ projectType,
7824
+ durationMs
7825
+ };
7826
+ this.printReport(resolvedPath, report, options?.fix);
7827
+ if (report.errors > 0) {
7828
+ process.exitCode = 1;
7829
+ }
7830
+ } catch (error) {
7831
+ spinner.fail(`Audit error: ${error instanceof Error ? error.message : "Unknown error"}`);
7832
+ process.exitCode = 1;
7833
+ }
7834
+ }
7835
+ async detectProjectType(projectPath) {
7836
+ const projectMdPath = path22.join(projectPath, HERASPEC_DIR_NAME, HERASPEC_MARKERS.PROJECT_MD);
7837
+ if (await FileSystemUtils.fileExists(projectMdPath)) {
7838
+ const content = await FileSystemUtils.readFile(projectMdPath);
7839
+ if (content.includes("perfex-module") || content.includes("perfex")) return "perfex-module";
7840
+ if (content.includes("wordpress-plugin")) return "wordpress-plugin";
7841
+ if (content.includes("wordpress-theme")) return "wordpress-theme";
7842
+ }
7843
+ const entries = await FileSystemUtils.readDirectory(projectPath);
7844
+ for (const entry of entries) {
7845
+ if (entry.endsWith(".php")) {
7846
+ const fileContent = await FileSystemUtils.readFile(path22.join(projectPath, entry));
7847
+ if (fileContent.includes("register_activation_hook") || fileContent.includes("hooks()->add_action")) {
7848
+ return "perfex-module";
7849
+ }
7850
+ if (fileContent.includes("Plugin Name:") || fileContent.includes("add_action(")) {
7851
+ return "wordpress-plugin";
7852
+ }
7853
+ }
7854
+ }
7855
+ return "generic-php";
7856
+ }
7857
+ async collectFiles(rootDir) {
7858
+ const files = [];
7859
+ const ignoreDirs = /* @__PURE__ */ new Set([
7860
+ "node_modules",
7861
+ ".git",
7862
+ "dist",
7863
+ "build",
7864
+ "vendor",
7865
+ "uploads",
7866
+ "heraspec",
7867
+ ".heraspec",
7868
+ ".agents",
7869
+ ".ai",
7870
+ "ScreenShot",
7871
+ "tests",
7872
+ "test",
7873
+ "scratch"
7874
+ ]);
7875
+ const walk = async (currentDir) => {
7876
+ const entries = await fs3.readdir(currentDir, { withFileTypes: true });
7877
+ for (const entry of entries) {
7878
+ if (entry.isDirectory()) {
7879
+ if (!ignoreDirs.has(entry.name)) {
7880
+ await walk(path22.join(currentDir, entry.name));
7881
+ }
7882
+ } else if (entry.isFile()) {
7883
+ files.push(path22.join(currentDir, entry.name));
7884
+ }
7885
+ }
7886
+ };
7887
+ await walk(rootDir);
7888
+ return files;
7889
+ }
7890
+ async auditPhpGuards(files, projectType, fix = false) {
7891
+ const phpFiles = files.filter((f) => f.endsWith(".php"));
7892
+ const isWp = projectType.includes("wordpress");
7893
+ const guardPattern = isWp ? /defined\s*\(\s*['"]ABSPATH['"]\s*\)/i : /defined\s*\(\s*['"]BASEPATH['"]\s*\)/i;
7894
+ const requiredGuard = isWp ? "defined('ABSPATH') or exit;" : "defined('BASEPATH') or exit('No direct script access allowed');";
7895
+ for (const file of phpFiles) {
7896
+ const content = await FileSystemUtils.readFile(file);
7897
+ if (!guardPattern.test(content)) {
7898
+ if (fix) {
7899
+ const updated = content.replace(/^<\?php\s*/i, `<?php
7900
+ ${requiredGuard}
7901
+
7902
+ `);
7903
+ await FileSystemUtils.writeFile(file, updated);
7904
+ this.passedCount++;
7905
+ this.issues.push({
7906
+ type: "info",
7907
+ rule: "PHP Direct Access Guard",
7908
+ file,
7909
+ message: `Auto-fixed: Added direct access guard to ${path22.basename(file)}`
7910
+ });
7911
+ } else {
7912
+ this.issues.push({
7913
+ type: "error",
7914
+ rule: "PHP Direct Access Guard",
7915
+ file,
7916
+ line: 1,
7917
+ message: `Missing direct script access guard (${isWp ? "ABSPATH" : "BASEPATH"}).`,
7918
+ suggestion: `Add "${requiredGuard}" at the top of the file.`,
7919
+ fixable: true
7920
+ });
7921
+ }
7922
+ } else {
7923
+ this.passedCount++;
7924
+ }
7925
+ }
7926
+ }
7927
+ async auditZeroInlineCode(files) {
7928
+ const viewFiles = files.filter((f) => f.includes("views") || f.includes("templates") || f.endsWith(".html"));
7929
+ for (const file of viewFiles) {
7930
+ const content = await FileSystemUtils.readFile(file);
7931
+ const lines = content.split("\n");
7932
+ for (let i = 0; i < lines.length; i++) {
7933
+ const line = lines[i];
7934
+ if (/<script\b[^>]*>/i.test(line) && !line.includes('type="application/ld+json"') && !line.includes('type="application/json"')) {
7935
+ this.issues.push({
7936
+ type: "error",
7937
+ rule: "Zero Inline JavaScript",
7938
+ file,
7939
+ line: i + 1,
7940
+ message: `Found inline <script> tag in view template.`,
7941
+ suggestion: "Move all logic to external standalone .js files in assets/js/ and compile to dist/."
7942
+ });
7943
+ }
7944
+ if (/<style\b[^>]*>/i.test(line)) {
7945
+ this.issues.push({
7946
+ type: "error",
7947
+ rule: "Zero Inline CSS",
7948
+ file,
7949
+ line: i + 1,
7950
+ message: `Found inline <style> tag in view template.`,
7951
+ suggestion: "Move all styles to external stylesheets in assets/css/."
7952
+ });
7953
+ }
7954
+ if (/\bstyle\s*=\s*["'][^"']+["']/i.test(line)) {
7955
+ this.issues.push({
7956
+ type: "warning",
7957
+ rule: "Zero Inline Style Attributes",
7958
+ file,
7959
+ line: i + 1,
7960
+ message: `Found inline style="..." attribute in HTML element.`,
7961
+ suggestion: "Use semantic CSS utility classes in external stylesheets."
7962
+ });
7963
+ }
7964
+ }
7965
+ this.passedCount++;
7966
+ }
7967
+ }
7968
+ async auditTriggerWords(files) {
7969
+ const codeFiles = files.filter((f) => f.endsWith(".php") || f.endsWith(".js"));
7970
+ const riskyWords = [
7971
+ { word: "injectStyles", reason: "Triggers AST scanner code/script injection alerts", replacement: "extendStyles or applyStyles" },
7972
+ { word: "injectScript", reason: "Triggers AST scanner code/script injection alerts", replacement: "enqueueScript or appendScript" },
7973
+ { word: "_seeder.php", reason: "Flagged by bot scanners as potential database tampering backdoor", replacement: "_demo_data.php" },
7974
+ { word: "bypass", reason: "Flagged as potential authentication or authorization bypass vulnerability", replacement: "permit or allow" }
7975
+ ];
7976
+ for (const file of codeFiles) {
7977
+ const content = await FileSystemUtils.readFile(file);
7978
+ for (const item of riskyWords) {
7979
+ if (content.includes(item.word)) {
7980
+ this.issues.push({
7981
+ type: "warning",
7982
+ rule: "Static Analysis Scanner Neutrality",
7983
+ file,
7984
+ message: `Found high-risk token "${item.word}": ${item.reason}.`,
7985
+ suggestion: `Replace with neutral terminology like "${item.replacement}".`
7986
+ });
7987
+ }
7988
+ }
7989
+ this.passedCount++;
7990
+ }
7991
+ }
7992
+ async auditSessionConcurrency(files) {
7993
+ const controllerFiles = files.filter((f) => f.includes("controllers") && f.endsWith(".php"));
7994
+ for (const file of controllerFiles) {
7995
+ const content = await FileSystemUtils.readFile(file);
7996
+ const lines = content.split("\n");
7997
+ let insideSearchMethod = false;
7998
+ let hasSessionClose = false;
7999
+ let methodStartLine = 1;
8000
+ for (let i = 0; i < lines.length; i++) {
8001
+ const line = lines[i];
8002
+ if (/public\s+function\s+(search|autocomplete|lookup|get_)/i.test(line)) {
8003
+ insideSearchMethod = true;
8004
+ hasSessionClose = false;
8005
+ methodStartLine = i + 1;
8006
+ }
8007
+ if (insideSearchMethod) {
8008
+ if (line.includes("session_write_close()")) {
8009
+ hasSessionClose = true;
8010
+ }
8011
+ if (line.includes("function ") && i + 1 > methodStartLine) {
8012
+ if (!hasSessionClose) {
8013
+ this.issues.push({
8014
+ type: "warning",
8015
+ rule: "Concurrency & Session Lock Prevention",
8016
+ file,
8017
+ line: methodStartLine,
8018
+ message: `AJAX read/search method does not release PHP session file lock.`,
8019
+ suggestion: `Add "session_write_close();" at the start of the method to support non-blocking concurrent requests.`
8020
+ });
8021
+ }
8022
+ insideSearchMethod = false;
8023
+ }
8024
+ }
8025
+ }
8026
+ this.passedCount++;
8027
+ }
8028
+ }
8029
+ async auditLanguageParity(rootDir) {
8030
+ const enLangDir = path22.join(rootDir, "language", "english");
8031
+ const viLangDir = path22.join(rootDir, "language", "vietnamese");
8032
+ if (!await FileSystemUtils.fileExists(enLangDir)) return;
8033
+ const enFiles = (await FileSystemUtils.readDirectory(enLangDir)).filter((f) => f.endsWith("_lang.php"));
8034
+ for (const langFile of enFiles) {
8035
+ const enPath = path22.join(enLangDir, langFile);
8036
+ const viPath = path22.join(viLangDir, langFile);
8037
+ const enKeys = this.extractLangKeys(await FileSystemUtils.readFile(enPath));
8038
+ if (await FileSystemUtils.fileExists(viPath)) {
8039
+ const viKeys = this.extractLangKeys(await FileSystemUtils.readFile(viPath));
8040
+ const missingInVi = [...enKeys].filter((k) => !viKeys.has(k));
8041
+ const missingInEn = [...viKeys].filter((k) => !enKeys.has(k));
8042
+ if (missingInVi.length > 0) {
8043
+ this.issues.push({
8044
+ type: "warning",
8045
+ rule: "Internationalization (i18n) Parity",
8046
+ file: viPath,
8047
+ message: `Vietnamese catalog is missing ${missingInVi.length} key(s) found in English: ${missingInVi.slice(0, 3).join(", ")}${missingInVi.length > 3 ? "..." : ""}`,
8048
+ suggestion: "Maintain 100% parity across all language catalogs."
8049
+ });
8050
+ }
8051
+ if (missingInEn.length > 0) {
8052
+ this.issues.push({
8053
+ type: "warning",
8054
+ rule: "Internationalization (i18n) Parity",
8055
+ file: enPath,
8056
+ message: `English catalog is missing ${missingInEn.length} key(s) found in Vietnamese: ${missingInEn.slice(0, 3).join(", ")}${missingInEn.length > 3 ? "..." : ""}`,
8057
+ suggestion: "Maintain 100% parity across all language catalogs."
8058
+ });
8059
+ }
8060
+ if (missingInVi.length === 0 && missingInEn.length === 0) {
8061
+ this.passedCount++;
8062
+ }
8063
+ }
8064
+ }
8065
+ }
8066
+ extractLangKeys(content) {
8067
+ const keys = /* @__PURE__ */ new Set();
8068
+ const matches = content.matchAll(/\$lang\[['"]([^'"]+)['"]\]/g);
8069
+ for (const match of matches) {
8070
+ keys.add(match[1]);
8071
+ }
8072
+ return keys;
8073
+ }
8074
+ async auditEmojis(files) {
8075
+ const codeFiles = files.filter((f) => f.endsWith(".php") || f.endsWith(".js") || f.endsWith(".css"));
8076
+ const emojiRegex = /[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/u;
8077
+ for (const file of codeFiles) {
8078
+ const content = await FileSystemUtils.readFile(file);
8079
+ const lines = content.split("\n");
8080
+ for (let i = 0; i < lines.length; i++) {
8081
+ if (emojiRegex.test(lines[i])) {
8082
+ this.issues.push({
8083
+ type: "info",
8084
+ rule: "Enterprise Typography & Zero-Emoji",
8085
+ file,
8086
+ line: i + 1,
8087
+ message: `Found Unicode emoji in enterprise source code or comment.`,
8088
+ suggestion: "Remove emojis to maintain clean, enterprise-grade typography."
8089
+ });
8090
+ }
8091
+ }
8092
+ this.passedCount++;
8093
+ }
8094
+ }
8095
+ async auditPackagingRules(rootDir) {
8096
+ const devFiles = ["package.json", "webpack.config.js"];
8097
+ const hasDevFiles = await Promise.all(devFiles.map((f) => FileSystemUtils.fileExists(path22.join(rootDir, f))));
8098
+ const hasDeployScript = await FileSystemUtils.fileExists(path22.join(rootDir, "deploy.ps1"));
8099
+ if (hasDevFiles.some(Boolean) && !hasDeployScript) {
8100
+ this.issues.push({
8101
+ type: "warning",
8102
+ rule: "Clean Release Packaging",
8103
+ file: rootDir,
8104
+ message: "Module contains build scripts (package.json/webpack) but lacks an automated packaging filter (deploy.ps1 or heraspec pack).",
8105
+ suggestion: "Ensure build scripts are strictly stripped from final release zip."
8106
+ });
8107
+ } else {
8108
+ this.passedCount++;
8109
+ }
8110
+ }
8111
+ printReport(targetPath, report, fix = false) {
8112
+ console.log("\n" + "\u2550".repeat(65));
8113
+ console.log(chalk15.bold(`\u{1F4CB} HeraSpec Code Quality & Security Audit Report`));
8114
+ console.log(`\u{1F4CD} Target: ${chalk15.gray(targetPath)}`);
8115
+ console.log(`\u{1F4E6} Type: ${chalk15.cyan(report.projectType)}`);
8116
+ console.log(`\u23F1 Time: ${chalk15.gray(report.durationMs + "ms")}`);
8117
+ console.log("\u2550".repeat(65) + "\n");
8118
+ if (report.issues.length === 0) {
8119
+ console.log(chalk15.green.bold("\u{1F389} 100% COMPLIANT! All quality, security & clean standards passed.\n"));
8120
+ return;
8121
+ }
8122
+ for (const issue of report.issues) {
8123
+ const relFile = path22.relative(targetPath, issue.file) || issue.file;
8124
+ const loc = issue.line ? `:${issue.line}` : "";
8125
+ const tag = issue.type === "error" ? chalk15.bgRed.black(" ERROR ") : issue.type === "warning" ? chalk15.bgYellow.black(" WARN ") : chalk15.bgCyan.black(" INFO ");
8126
+ console.log(`${tag} ${chalk15.bold(issue.rule)}`);
8127
+ console.log(` ${chalk15.gray(relFile + loc)}: ${issue.message}`);
8128
+ if (issue.suggestion) {
8129
+ console.log(` ${chalk15.cyan("\u{1F4A1} Suggestion:")} ${issue.suggestion}`);
8130
+ }
8131
+ console.log();
8132
+ }
8133
+ console.log("\u2500".repeat(65));
8134
+ console.log(
8135
+ `Summary: ${chalk15.green(`${report.passed} checks passed`)}, ${report.warnings > 0 ? chalk15.yellow(`${report.warnings} warnings`) : "0 warnings"}, ${report.errors > 0 ? chalk15.red.bold(`${report.errors} errors`) : chalk15.green("0 errors")}`
8136
+ );
8137
+ if (report.errors > 0) {
8138
+ console.log(chalk15.red("\n\u274C Codebase failed critical quality/security checks. Please resolve errors before publishing."));
8139
+ if (!fix) {
8140
+ console.log(chalk15.gray('Tip: Run "heraspec audit --fix" to automatically remediate fixable issues.\n'));
8141
+ }
8142
+ } else {
8143
+ console.log(chalk15.green.bold("\n\u2714 Ready for production release!\n"));
8144
+ }
8145
+ }
8146
+ };
8147
+
8148
+ // src/commands/create.ts
8149
+ init_file_system();
8150
+ init_skill();
8151
+ import path23 from "path";
8152
+ import chalk16 from "chalk";
8153
+ import ora13 from "ora";
8154
+ var CreateCommand = class {
8155
+ async execute(name, options) {
8156
+ if (!name) {
8157
+ console.error(chalk16.red("Error: Please specify a name"));
8158
+ console.log("Usage: heraspec create <name> --type <perfex-module|wordpress-plugin|wordpress-theme>");
8159
+ process.exitCode = 1;
8160
+ return;
8161
+ }
8162
+ const projectType = options.type || "perfex-module";
8163
+ const cleanName = name.toLowerCase().replace(/[^a-z0-9_-]/g, "_");
8164
+ const pascalName = cleanName.split(/[_-]/).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
8165
+ const upperName = cleanName.toUpperCase().replace(/-/g, "_");
8166
+ const friendlyTitle = options.title || pascalName;
8167
+ const description = options.description || `${friendlyTitle} component`;
8168
+ const targetDir = options.out ? path23.resolve(options.out, cleanName) : path23.resolve(process.cwd(), projectType.includes("perfex") ? path23.join("modules", cleanName) : cleanName);
8169
+ const spinner = ora13(`Scaffolding ${chalk16.cyan(projectType)} "${cleanName}"...`).start();
8170
+ try {
8171
+ if (await FileSystemUtils.fileExists(targetDir)) {
8172
+ spinner.fail(`Target directory already exists: ${targetDir}`);
8173
+ process.exitCode = 1;
8174
+ return;
8175
+ }
8176
+ await FileSystemUtils.createDirectory(targetDir);
8177
+ if (projectType === "perfex-module") {
8178
+ await this.scaffoldPerfexModule(targetDir, {
8179
+ cleanName,
8180
+ pascalName,
8181
+ upperName,
8182
+ friendlyTitle,
8183
+ description
8184
+ });
8185
+ } else if (projectType === "wordpress-plugin") {
8186
+ await this.scaffoldWordPressPlugin(targetDir, {
8187
+ cleanName,
8188
+ pascalName,
8189
+ upperName,
8190
+ friendlyTitle,
8191
+ description
8192
+ });
8193
+ } else {
8194
+ spinner.fail(`Scaffolding template for "${projectType}" is not yet supported.`);
8195
+ process.exitCode = 1;
8196
+ return;
8197
+ }
8198
+ spinner.text = "Initializing HeraSpec and installing skill suite...";
8199
+ const initCommand = new InitCommand();
8200
+ await initCommand.execute(targetDir);
8201
+ const skillCommand = new SkillCommand();
8202
+ if (projectType === "perfex-module") {
8203
+ await skillCommand.add("perfex-module", void 0, targetDir);
8204
+ } else if (projectType === "wordpress-plugin") {
8205
+ await skillCommand.add("plugin-standard", "wordpress", targetDir);
8206
+ }
8207
+ spinner.succeed(chalk16.green(`Successfully created ${projectType} "${cleanName}"!`));
8208
+ console.log(`
8209
+ \u{1F4CD} Location: ${chalk16.gray(targetDir)}`);
8210
+ console.log("\n\u{1F680} Next steps:");
8211
+ console.log(chalk16.cyan(` cd ${path23.relative(process.cwd(), targetDir) || "."}`));
8212
+ console.log(chalk16.gray(" heraspec audit # Run code quality & security checks"));
8213
+ console.log(chalk16.gray(" heraspec pack # Package for production release\n"));
8214
+ } catch (error) {
8215
+ spinner.fail(`Failed to create project: ${error instanceof Error ? error.message : "Unknown error"}`);
8216
+ process.exitCode = 1;
8217
+ }
8218
+ }
8219
+ async scaffoldPerfexModule(targetDir, meta) {
8220
+ const dirs = [
8221
+ "controllers",
8222
+ "models",
8223
+ "helpers",
8224
+ "libraries",
8225
+ "views/admin",
8226
+ "language/english",
8227
+ "language/vietnamese",
8228
+ "assets/css/admin",
8229
+ "assets/js/admin",
8230
+ "assets/js/lib",
8231
+ "assets/css/lib",
8232
+ "dist/assets/css",
8233
+ "dist/assets/js",
8234
+ "tests",
8235
+ "documentations"
8236
+ ];
8237
+ for (const d of dirs) {
8238
+ await FileSystemUtils.createDirectory(path23.join(targetDir, d));
8239
+ }
8240
+ const { cleanName, pascalName, upperName, friendlyTitle, description } = meta;
8241
+ const mainBootstrap = `<?php
8242
+ defined('BASEPATH') or exit('No direct script access allowed');
8243
+
8244
+ /*
8245
+ Module Name: ${friendlyTitle}
8246
+ Description: ${description}
8247
+ Version: 1.0.0
8248
+ Requires at least: 2.9.*
8249
+ Author: PolyXGO
8250
+ Author URI: https://codecanyon.net/user/polyxgo
8251
+ */
8252
+
8253
+ define('${upperName}_MODULE_NAME', '${cleanName}');
8254
+ define('${upperName}_VERSION', '1.0.0');
8255
+
8256
+ register_activation_hook(${upperName}_MODULE_NAME, '${cleanName}_activation_hook');
8257
+ register_deactivation_hook(${upperName}_MODULE_NAME, '${cleanName}_deactivation_hook');
8258
+ register_uninstall_hook(${upperName}_MODULE_NAME, '${cleanName}_uninstall_hook');
8259
+
8260
+ function ${cleanName}_activation_hook()
8261
+ {
8262
+ $CI = &get_instance();
8263
+ require_once(__DIR__ . '/install.php');
8264
+ }
8265
+
8266
+ function ${cleanName}_deactivation_hook()
8267
+ {
8268
+ }
8269
+
8270
+ function ${cleanName}_uninstall_hook()
8271
+ {
8272
+ require_once(__DIR__ . '/uninstall.php');
8273
+ }
8274
+
8275
+ register_language_files(${upperName}_MODULE_NAME, [${upperName}_MODULE_NAME]);
8276
+
8277
+ $CI = &get_instance();
8278
+ $CI->load->helper(${upperName}_MODULE_NAME . '/${cleanName}');
8279
+
8280
+ hooks()->add_action('admin_init', '${cleanName}_init_menu_items');
8281
+
8282
+ function ${cleanName}_init_menu_items()
8283
+ {
8284
+ $CI = &get_instance();
8285
+ if (has_permission('${cleanName}', '', 'view')) {
8286
+ $CI->app_menu->add_sidebar_menu_item('${cleanName}-menu', [
8287
+ 'name' => _l('${cleanName}_menu_title'),
8288
+ 'href' => admin_url('${cleanName}'),
8289
+ 'icon' => 'fa-solid fa-cube',
8290
+ 'position' => 30,
8291
+ ]);
8292
+ }
8293
+ }
8294
+
8295
+ hooks()->add_action('app_admin_head', '${cleanName}_enqueue_admin_head');
8296
+ hooks()->add_action('app_admin_footer', '${cleanName}_enqueue_admin_footer');
8297
+
8298
+ function ${cleanName}_enqueue_admin_head()
8299
+ {
8300
+ $config = [
8301
+ 'moduleName' => ${upperName}_MODULE_NAME,
8302
+ 'version' => ${upperName}_VERSION,
8303
+ 'adminUrl' => admin_url('${cleanName}/'),
8304
+ 'csrfToken' => get_instance()->security->get_csrf_hash(),
8305
+ ];
8306
+ $lang = [
8307
+ 'confirmDelete' => _l('${cleanName}_confirm_delete'),
8308
+ 'saveSuccess' => _l('${cleanName}_saved_successfully'),
8309
+ ];
8310
+
8311
+ echo '<script>' . PHP_EOL;
8312
+ echo 'window.' . '${upperName}_CONFIG = ' . json_encode($config) . ';' . PHP_EOL;
8313
+ echo 'window.' . '${upperName}_LANG = ' . json_encode($lang) . ';' . PHP_EOL;
8314
+ echo '</script>' . PHP_EOL;
8315
+
8316
+ echo ${cleanName}_helper::render_module_css('admin/${cleanName}_admin');
8317
+ }
8318
+
8319
+ function ${cleanName}_enqueue_admin_footer()
8320
+ {
8321
+ echo ${cleanName}_helper::render_module_js('admin/${cleanName}_admin');
8322
+ }
8323
+ `;
8324
+ await FileSystemUtils.writeFile(path23.join(targetDir, `${cleanName}.php`), mainBootstrap);
8325
+ const installPhp = `<?php
8326
+ defined('BASEPATH') or exit('No direct script access allowed');
8327
+
8328
+ $CI = &get_instance();
8329
+
8330
+ if (!$CI->db->table_exists(db_prefix() . '${cleanName}_items')) {
8331
+ $CI->db->query('CREATE TABLE \`' . db_prefix() . '${cleanName}_items\` (
8332
+ \`id\` INT(11) NOT NULL AUTO_INCREMENT,
8333
+ \`rel_type\` VARCHAR(40) NOT NULL,
8334
+ \`rel_id\` INT(11) NOT NULL,
8335
+ \`title\` VARCHAR(255) NOT NULL,
8336
+ \`description\` TEXT NULL,
8337
+ \`status\` TINYINT(1) NOT NULL DEFAULT 1,
8338
+ \`date_created\` DATETIME NOT NULL,
8339
+ \`created_by\` INT(11) NOT NULL,
8340
+ PRIMARY KEY (\`id\`),
8341
+ KEY \`idx_rel_lookup\` (\`rel_type\`, \`rel_id\`),
8342
+ KEY \`idx_status_created\` (\`status\`, \`date_created\`)
8343
+ ) ENGINE=InnoDB DEFAULT CHARSET=' . $CI->db->char_set . ';');
8344
+ }
8345
+
8346
+ if (empty(get_option('${cleanName}_enabled'))) {
8347
+ add_option('${cleanName}_enabled', '1', 1);
8348
+ }
8349
+ `;
8350
+ await FileSystemUtils.writeFile(path23.join(targetDir, "install.php"), installPhp);
8351
+ const uninstallPhp = `<?php
8352
+ defined('BASEPATH') or exit('No direct script access allowed');
8353
+
8354
+ $CI = &get_instance();
8355
+ delete_option('${cleanName}_enabled');
8356
+ `;
8357
+ await FileSystemUtils.writeFile(path23.join(targetDir, "uninstall.php"), uninstallPhp);
8358
+ const helperPhp = `<?php
8359
+ defined('BASEPATH') or exit('No direct script access allowed');
8360
+
8361
+ class ${cleanName}_helper
8362
+ {
8363
+ public static function get_file_timestamp($relative_path)
8364
+ {
8365
+ $full_path = rtrim(FCPATH, '/\\\\') . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relative_path);
8366
+ return file_exists($full_path) ? filemtime($full_path) : '1.0.0';
8367
+ }
8368
+
8369
+ public static function render_module_js($subpath)
8370
+ {
8371
+ $rel_dist = 'dist/assets/js/' . $subpath . '.min.js';
8372
+ $rel_src = 'assets/js/' . $subpath . '.js';
8373
+
8374
+ $full_dist = rtrim(FCPATH, '/\\\\') . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . ${upperName}_MODULE_NAME . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $rel_dist);
8375
+ $chosen = file_exists($full_dist) ? $rel_dist : $rel_src;
8376
+ $path = 'modules/' . ${upperName}_MODULE_NAME . '/' . $chosen;
8377
+ $url = module_dir_url(${upperName}_MODULE_NAME, $chosen);
8378
+ $v = self::get_file_timestamp($path);
8379
+
8380
+ return '<script src="' . $url . '?v=' . $v . '"></script>' . PHP_EOL;
8381
+ }
8382
+
8383
+ public static function render_module_css($subpath)
8384
+ {
8385
+ $rel_dist = 'dist/assets/css/' . $subpath . '.min.css';
8386
+ $rel_src = 'assets/css/' . $subpath . '.css';
8387
+
8388
+ $full_dist = rtrim(FCPATH, '/\\\\') . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . ${upperName}_MODULE_NAME . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $rel_dist);
8389
+ $chosen = file_exists($full_dist) ? $rel_dist : $rel_src;
8390
+ $path = 'modules/' . ${upperName}_MODULE_NAME . '/' . $chosen;
8391
+ $url = module_dir_url(${upperName}_MODULE_NAME, $chosen);
8392
+ $v = self::get_file_timestamp($path);
8393
+
8394
+ return '<link rel="stylesheet" href="' . $url . '?v=' . $v . '">' . PHP_EOL;
8395
+ }
8396
+ }
8397
+ `;
8398
+ await FileSystemUtils.writeFile(path23.join(targetDir, "helpers", `${cleanName}_helper.php`), helperPhp);
8399
+ const adminController = `<?php
8400
+ defined('BASEPATH') or exit('No direct script access allowed');
8401
+
8402
+ class ${pascalName} extends AdminController
8403
+ {
8404
+ public function __construct()
8405
+ {
8406
+ parent::__construct();
8407
+ $this->load->model('${cleanName}/${cleanName}_model');
8408
+ }
8409
+
8410
+ public function index()
8411
+ {
8412
+ if (!has_permission('${cleanName}', '', 'view')) {
8413
+ access_denied('${cleanName}');
8414
+ }
8415
+
8416
+ $data['title'] = _l('${cleanName}_management');
8417
+ $data['items'] = $this->${cleanName}_model->get_all();
8418
+
8419
+ $this->load->view('${cleanName}/admin/manage', $data);
8420
+ }
8421
+ }
8422
+ `;
8423
+ await FileSystemUtils.writeFile(path23.join(targetDir, "controllers", `${pascalName}.php`), adminController);
8424
+ const apiController = `<?php
8425
+ defined('BASEPATH') or exit('No direct script access allowed');
8426
+
8427
+ class Api extends AdminController
8428
+ {
8429
+ public function __construct()
8430
+ {
8431
+ parent::__construct();
8432
+ $this->load->model('${cleanName}/${cleanName}_model');
8433
+ }
8434
+
8435
+ public function search()
8436
+ {
8437
+ session_write_close();
8438
+
8439
+ if (!has_permission('${cleanName}', '', 'view')) {
8440
+ ajax_access_denied();
8441
+ }
8442
+
8443
+ $query = $this->input->get('q', true);
8444
+ $results = $this->${cleanName}_model->search($query);
8445
+
8446
+ echo json_encode(['success' => true, 'data' => $results]);
8447
+ }
8448
+ }
8449
+ `;
8450
+ await FileSystemUtils.writeFile(path23.join(targetDir, "controllers", "Api.php"), apiController);
8451
+ const modelPhp = `<?php
8452
+ defined('BASEPATH') or exit('No direct script access allowed');
8453
+
8454
+ class ${cleanName}_model extends App_Model
8455
+ {
8456
+ protected $table;
8457
+
8458
+ public function __construct()
8459
+ {
8460
+ parent::__construct();
8461
+ $this->table = db_prefix() . '${cleanName}_items';
8462
+ }
8463
+
8464
+ public function get_all()
8465
+ {
8466
+ $this->db->order_by('date_created', 'DESC');
8467
+ return $this->db->get($this->table)->result_array();
8468
+ }
8469
+
8470
+ public function search($query, $limit = 20)
8471
+ {
8472
+ $this->db->select('id, rel_type, rel_id, title, status');
8473
+ $this->db->from($this->table);
8474
+ if (!empty($query)) {
8475
+ $this->db->like('title', $query);
8476
+ }
8477
+ $this->db->where('status', 1);
8478
+ $this->db->limit($limit);
8479
+ return $this->db->get()->result_array();
8480
+ }
8481
+ }
8482
+ `;
8483
+ await FileSystemUtils.writeFile(path23.join(targetDir, "models", `${cleanName}_model.php`), modelPhp);
8484
+ const enLang = `<?php
8485
+ defined('BASEPATH') or exit('No direct script access allowed');
8486
+
8487
+ $lang['${cleanName}_menu_title'] = '${friendlyTitle}';
8488
+ $lang['${cleanName}_management'] = '${friendlyTitle} Management';
8489
+ $lang['${cleanName}_confirm_delete'] = 'Are you sure you want to delete this item?';
8490
+ $lang['${cleanName}_saved_successfully'] = 'Saved successfully.';
8491
+ `;
8492
+ await FileSystemUtils.writeFile(path23.join(targetDir, "language", "english", `${cleanName}_lang.php`), enLang);
8493
+ const viLang = `<?php
8494
+ defined('BASEPATH') or exit('No direct script access allowed');
8495
+
8496
+ $lang['${cleanName}_menu_title'] = '${friendlyTitle}';
8497
+ $lang['${cleanName}_management'] = 'Qu\u1EA3n l\xFD ${friendlyTitle}';
8498
+ $lang['${cleanName}_confirm_delete'] = 'B\u1EA1n c\xF3 ch\u1EAFc ch\u1EAFn mu\u1ED1n x\xF3a m\u1EE5c n\xE0y?';
8499
+ $lang['${cleanName}_saved_successfully'] = 'L\u01B0u th\xE0nh c\xF4ng.';
8500
+ `;
8501
+ await FileSystemUtils.writeFile(path23.join(targetDir, "language", "vietnamese", `${cleanName}_lang.php`), viLang);
8502
+ const adminView = `<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
8503
+ <?php init_head(); ?>
8504
+ <div id="wrapper">
8505
+ <div class="content">
8506
+ <div class="row">
8507
+ <div class="col-md-12">
8508
+ <div class="panel_s">
8509
+ <div class="panel-body">
8510
+ <h4 class="no-margin font-bold"><?php echo html_escape($title); ?></h4>
8511
+ <hr class="hr-panel-heading" />
8512
+ <div class="${cleanName}-container" data-module="${cleanName}">
8513
+ <p><?php echo _l('${cleanName}_management'); ?></p>
8514
+ </div>
8515
+ </div>
8516
+ </div>
8517
+ </div>
8518
+ </div>
8519
+ </div>
8520
+ </div>
8521
+ <?php init_tail(); ?>
8522
+ `;
8523
+ await FileSystemUtils.writeFile(path23.join(targetDir, "views", "admin", "manage.php"), adminView);
8524
+ const adminJs = `window.addEventListener('load', function () {
8525
+ (function ($) {
8526
+ 'use strict';
8527
+ // ${friendlyTitle} Admin Logic
8528
+ })(typeof jQuery !== 'undefined' ? jQuery : window.$);
8529
+ });
8530
+ `;
8531
+ await FileSystemUtils.writeFile(path23.join(targetDir, "assets", "js", "admin", `${cleanName}_admin.js`), adminJs);
8532
+ const adminCss = `.${cleanName}-container {
8533
+ padding: 10px 0;
8534
+ }
8535
+ `;
8536
+ await FileSystemUtils.writeFile(path23.join(targetDir, "assets", "css", "admin", `${cleanName}_admin.css`), adminCss);
8537
+ const testPhp = `<?php
8538
+ class Test_${pascalName}
8539
+ {
8540
+ public function run()
8541
+ {
8542
+ echo "Running automated quality tests for ${pascalName}...\\n";
8543
+ $files = glob(__DIR__ . '/../*.php');
8544
+ $passed = 0;
8545
+ foreach ($files as $file) {
8546
+ $content = file_get_contents($file);
8547
+ assert(strpos($content, "defined('BASEPATH')") !== false, basename($file) . " missing BASEPATH guard.");
8548
+ $passed++;
8549
+ }
8550
+ echo "All {$passed} checks passed 100%!\\n";
8551
+ }
8552
+ }
8553
+ $test = new Test_${pascalName}();
8554
+ $test->run();
8555
+ `;
8556
+ await FileSystemUtils.writeFile(path23.join(targetDir, "tests", `Test_${pascalName}.php`), testPhp);
8557
+ }
8558
+ async scaffoldWordPressPlugin(targetDir, meta) {
8559
+ const { cleanName, pascalName, upperName, friendlyTitle, description } = meta;
8560
+ const dirs = ["includes", "admin", "public", "languages", "assets/css", "assets/js"];
8561
+ for (const d of dirs) {
8562
+ await FileSystemUtils.createDirectory(path23.join(targetDir, d));
8563
+ }
8564
+ const mainPlugin = `<?php
8565
+ /**
8566
+ * Plugin Name: ${friendlyTitle}
8567
+ * Description: ${description}
8568
+ * Version: 1.0.0
8569
+ * Author: PolyXGO
8570
+ * License: GPL v2 or later
8571
+ * Text Domain: ${cleanName}
8572
+ * Domain Path: /languages
8573
+ */
8574
+
8575
+ defined('ABSPATH') or exit;
8576
+
8577
+ define('${upperName}_VERSION', '1.0.0');
8578
+ define('${upperName}_PATH', plugin_dir_path(__FILE__));
8579
+ define('${upperName}_URL', plugin_dir_url(__FILE__));
8580
+
8581
+ register_activation_hook(__FILE__, '${cleanName}_activate');
8582
+ register_deactivation_hook(__FILE__, '${cleanName}_deactivate');
8583
+
8584
+ function ${cleanName}_activate() {
8585
+ }
8586
+
8587
+ function ${cleanName}_deactivate() {
8588
+ }
8589
+ `;
8590
+ await FileSystemUtils.writeFile(path23.join(targetDir, `${cleanName}.php`), mainPlugin);
8591
+ const uninstallPhp = `<?php
8592
+ defined('WP_UNINSTALL_PLUGIN') or exit;
8593
+ `;
8594
+ await FileSystemUtils.writeFile(path23.join(targetDir, "uninstall.php"), uninstallPhp);
8595
+ }
8596
+ };
8597
+
8598
+ // src/commands/pack.ts
8599
+ init_file_system();
8600
+ init_config();
8601
+ import path24 from "path";
8602
+ import os from "os";
8603
+ import { promises as fs4 } from "fs";
8604
+ import { execSync } from "child_process";
8605
+ import chalk17 from "chalk";
8606
+ import ora14 from "ora";
8607
+ var PackCommand = class {
8608
+ defaultExcludeDirs = /* @__PURE__ */ new Set([
8609
+ "node_modules",
8610
+ ".git",
8611
+ ".github",
8612
+ ".svn",
8613
+ ".vscode",
8614
+ ".idea",
8615
+ HERASPEC_DIR_NAME,
8616
+ ".heraspec",
8617
+ ".agents",
8618
+ ".ai",
8619
+ "scratch",
8620
+ "tests",
8621
+ "test",
8622
+ "tests-build",
8623
+ "cypress",
8624
+ "ScreenShot",
8625
+ "screenshots",
8626
+ "docs/internal",
8627
+ "_private_note",
8628
+ "releases"
8629
+ ]);
8630
+ defaultExcludeFiles = /* @__PURE__ */ new Set([
8631
+ "package.json",
8632
+ "package-lock.json",
8633
+ "webpack.config.js",
8634
+ "webpack.config.mjs",
8635
+ "tsconfig.json",
8636
+ "build.js",
8637
+ "rollup.config.js",
8638
+ "vite.config.js",
8639
+ ".gitignore",
8640
+ ".npmignore",
8641
+ ".editorconfig",
8642
+ "deploy.ps1",
8643
+ "phpunit.xml",
8644
+ "Thumbs.db",
8645
+ ".DS_Store"
8646
+ ]);
8647
+ async execute(targetPath = ".", options = {}) {
8648
+ const spinner = ora14("Preparing production release package...").start();
8649
+ const startTime = Date.now();
8650
+ try {
8651
+ const projectRoot = path24.resolve(targetPath);
8652
+ if (!await FileSystemUtils.fileExists(projectRoot)) {
8653
+ spinner.fail(`Target path does not exist: ${projectRoot}`);
8654
+ process.exitCode = 1;
8655
+ return;
8656
+ }
8657
+ const cleanName = options.name || await this.detectProjectName(projectRoot);
8658
+ const version2 = options.version || await this.detectProjectVersion(projectRoot);
8659
+ spinner.text = `Packaging ${chalk17.cyan(cleanName)} (v${version2})...`;
8660
+ const shouldBuild = options.build !== false;
8661
+ if (shouldBuild) {
8662
+ await this.buildAssetsIfConfigured(projectRoot, spinner);
8663
+ }
8664
+ const tempId = `heraspec-pack-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`;
8665
+ const stageBaseDir = path24.join(os.tmpdir(), tempId);
8666
+ const stageFolder = path24.join(stageBaseDir, cleanName);
8667
+ await FileSystemUtils.createDirectory(stageFolder);
8668
+ spinner.text = "Staging production files (filtering dev bloat)...";
8669
+ const fileCount = await this.stageProductionFiles(projectRoot, stageFolder);
8670
+ if (fileCount === 0) {
8671
+ spinner.fail("No valid production files found to package.");
8672
+ await FileSystemUtils.removeDirectory(stageBaseDir, true);
8673
+ process.exitCode = 1;
8674
+ return;
8675
+ }
8676
+ const outputDir = options.out ? path24.resolve(options.out) : path24.join(projectRoot, "releases");
8677
+ await FileSystemUtils.createDirectory(outputDir);
8678
+ const archiveName = `${cleanName}-v${version2}.zip`;
8679
+ const archivePath = path24.join(outputDir, archiveName);
8680
+ if (await FileSystemUtils.fileExists(archivePath)) {
8681
+ await FileSystemUtils.removeFile(archivePath);
8682
+ }
8683
+ spinner.text = `Compressing ${chalk17.cyan(archiveName)}...`;
8684
+ await this.createZipArchive(stageBaseDir, cleanName, archivePath);
8685
+ const archiveStat = await fs4.stat(archivePath);
8686
+ const sizeKb = (archiveStat.size / 1024).toFixed(1);
8687
+ const sizeMb = (archiveStat.size / (1024 * 1024)).toFixed(2);
8688
+ const displaySize = archiveStat.size >= 1024 * 1024 ? `${sizeMb} MB` : `${sizeKb} KB`;
8689
+ try {
8690
+ await FileSystemUtils.removeDirectory(stageBaseDir, true);
8691
+ } catch {
8692
+ }
8693
+ const elapsedMs = Date.now() - startTime;
8694
+ spinner.succeed(chalk17.green(`Packaged ${chalk17.bold(archiveName)} in ${elapsedMs}ms`));
8695
+ console.log("\n" + "\u2550".repeat(60));
8696
+ console.log(chalk17.bold("\u{1F4E6} Production Release Archive Ready"));
8697
+ console.log("\u2550".repeat(60));
8698
+ console.log(` File: ${chalk17.cyan(path24.relative(process.cwd(), archivePath) || archivePath)}`);
8699
+ console.log(` Size: ${chalk17.yellow(displaySize)} (${archiveStat.size.toLocaleString()} bytes)`);
8700
+ console.log(` Files: ${chalk17.green(fileCount)} files included`);
8701
+ console.log(` Root Folder: ${chalk17.cyan(cleanName + "/")}`);
8702
+ console.log(` Exclusions: ${chalk17.gray("node_modules, .git, tests, dev tools stripped")}`);
8703
+ console.log("\u2550".repeat(60) + "\n");
8704
+ } catch (error) {
8705
+ spinner.fail(`Packaging failed: ${error instanceof Error ? error.message : "Unknown error"}`);
8706
+ process.exitCode = 1;
8707
+ }
8708
+ }
8709
+ async detectProjectName(projectRoot) {
8710
+ const configPath = path24.join(projectRoot, HERASPEC_DIR_NAME, HERASPEC_MARKERS.CONFIG_YAML);
8711
+ if (await FileSystemUtils.fileExists(configPath)) {
8712
+ const content = await FileSystemUtils.readFile(configPath);
8713
+ const match = content.match(/projectName:\s*["']?([^"'\n\r]+)["']?/);
8714
+ if (match && match[1]) {
8715
+ return match[1].toLowerCase().replace(/[^a-z0-9_-]/g, "_");
8716
+ }
8717
+ }
8718
+ const entries = await fs4.readdir(projectRoot, { withFileTypes: true });
8719
+ for (const entry of entries) {
8720
+ if (entry.isFile() && entry.name.endsWith(".php")) {
8721
+ const filePath = path24.join(projectRoot, entry.name);
8722
+ const content = await FileSystemUtils.readFile(filePath);
8723
+ if (content.includes("Module Name:") || content.includes("Plugin Name:")) {
8724
+ return entry.name.replace(/\.php$/, "");
8725
+ }
8726
+ }
8727
+ }
8728
+ const packageJsonPath2 = path24.join(projectRoot, "package.json");
8729
+ if (await FileSystemUtils.fileExists(packageJsonPath2)) {
8730
+ try {
8731
+ const pkg = JSON.parse(await FileSystemUtils.readFile(packageJsonPath2));
8732
+ if (pkg.name) {
8733
+ return pkg.name.replace(/^@[^/]+\//, "").toLowerCase().replace(/[^a-z0-9_-]/g, "_");
8734
+ }
8735
+ } catch {
8736
+ }
8737
+ }
8738
+ return path24.basename(projectRoot).toLowerCase().replace(/[^a-z0-9_-]/g, "_");
8739
+ }
8740
+ async detectProjectVersion(projectRoot) {
8741
+ const entries = await fs4.readdir(projectRoot, { withFileTypes: true });
8742
+ for (const entry of entries) {
8743
+ if (entry.isFile() && entry.name.endsWith(".php")) {
8744
+ const filePath = path24.join(projectRoot, entry.name);
8745
+ const content = await FileSystemUtils.readFile(filePath);
8746
+ const headerMatch = content.match(/Version:\s*([0-9]+\.[0-9]+(?:\.[0-9]+)?)/i);
8747
+ if (headerMatch && headerMatch[1]) return headerMatch[1];
8748
+ const constMatch = content.match(/define\s*\(\s*['"][^'"]*VERSION['"]\s*,\s*['"]([0-9]+\.[0-9]+(?:\.[0-9]+)?)['"]\s*\)/i);
8749
+ if (constMatch && constMatch[1]) return constMatch[1];
8750
+ }
8751
+ }
8752
+ const packageJsonPath2 = path24.join(projectRoot, "package.json");
8753
+ if (await FileSystemUtils.fileExists(packageJsonPath2)) {
8754
+ try {
8755
+ const pkg = JSON.parse(await FileSystemUtils.readFile(packageJsonPath2));
8756
+ if (pkg.version) return pkg.version;
8757
+ } catch {
8758
+ }
8759
+ }
8760
+ return "1.0.0";
8761
+ }
8762
+ async buildAssetsIfConfigured(projectRoot, spinner) {
8763
+ const packageJsonPath2 = path24.join(projectRoot, "package.json");
8764
+ if (!await FileSystemUtils.fileExists(packageJsonPath2)) return;
8765
+ try {
8766
+ const pkg = JSON.parse(await FileSystemUtils.readFile(packageJsonPath2));
8767
+ if (!pkg.scripts || !pkg.scripts.build) return;
8768
+ spinner.text = "Running asset production build (npm run build)...";
8769
+ execSync("npm run build", {
8770
+ cwd: projectRoot,
8771
+ stdio: "pipe",
8772
+ timeout: 12e4
8773
+ });
8774
+ spinner.succeed("Asset production build completed successfully.");
8775
+ spinner.start();
8776
+ } catch (buildError) {
8777
+ spinner.warn(`Asset build command failed or timed out: ${buildError instanceof Error ? buildError.message : "Unknown error"}`);
8778
+ spinner.start();
8779
+ }
8780
+ }
8781
+ async stageProductionFiles(srcDir, destDir) {
8782
+ let fileCount = 0;
8783
+ const copyRecursive = async (currentSrc, currentDest) => {
8784
+ await fs4.mkdir(currentDest, { recursive: true });
8785
+ const entries = await fs4.readdir(currentSrc, { withFileTypes: true });
8786
+ for (const entry of entries) {
8787
+ const srcPath = path24.join(currentSrc, entry.name);
8788
+ const destPath = path24.join(currentDest, entry.name);
8789
+ if (entry.isDirectory()) {
8790
+ if (this.defaultExcludeDirs.has(entry.name)) continue;
8791
+ if (entry.name.startsWith(".")) continue;
8792
+ await copyRecursive(srcPath, destPath);
8793
+ } else if (entry.isFile()) {
8794
+ if (this.defaultExcludeFiles.has(entry.name)) continue;
8795
+ if (entry.name.startsWith(".")) continue;
8796
+ if (entry.name.endsWith(".test.php") || entry.name.endsWith(".spec.ts") || entry.name.endsWith(".log")) continue;
8797
+ await fs4.copyFile(srcPath, destPath);
8798
+ fileCount++;
8799
+ }
8800
+ }
8801
+ };
8802
+ await copyRecursive(srcDir, destDir);
8803
+ return fileCount;
8804
+ }
8805
+ async createZipArchive(stageBaseDir, folderToPack, zipDestination) {
8806
+ const isWindows = process.platform === "win32";
8807
+ try {
8808
+ execSync(`tar -a -cf "${zipDestination}" "${folderToPack}"`, {
8809
+ cwd: stageBaseDir,
8810
+ stdio: "pipe"
8811
+ });
8812
+ if (await FileSystemUtils.fileExists(zipDestination)) {
8813
+ return;
8814
+ }
8815
+ } catch {
8816
+ }
8817
+ if (isWindows) {
8818
+ try {
8819
+ const sourcePath = path24.join(stageBaseDir, folderToPack);
8820
+ const psCommand = `Compress-Archive -Path "${sourcePath}" -DestinationPath "${zipDestination}" -Force`;
8821
+ execSync(`powershell.exe -NoProfile -NonInteractive -Command "${psCommand}"`, {
8822
+ cwd: stageBaseDir,
8823
+ stdio: "pipe"
8824
+ });
8825
+ if (await FileSystemUtils.fileExists(zipDestination)) {
8826
+ return;
8827
+ }
8828
+ } catch (psErr) {
8829
+ throw new Error(`Compression failed via tar and PowerShell: ${psErr.message}`);
8830
+ }
8831
+ } else {
8832
+ try {
8833
+ execSync(`zip -r "${zipDestination}" "${folderToPack}"`, {
8834
+ cwd: stageBaseDir,
8835
+ stdio: "pipe"
8836
+ });
8837
+ if (await FileSystemUtils.fileExists(zipDestination)) {
8838
+ return;
8839
+ }
8840
+ } catch (zipErr) {
8841
+ throw new Error(`Compression failed via tar and zip: ${zipErr.message}`);
8842
+ }
8843
+ }
8844
+ throw new Error("Could not create archive. Please ensure tar, zip, or PowerShell is installed.");
8845
+ }
8846
+ };
8847
+
7539
8848
  // src/cli/index.ts
7540
8849
  var require4 = createRequire3(import.meta.url);
7541
8850
  var __filename3 = fileURLToPath3(import.meta.url);
@@ -7867,5 +9176,32 @@ exploreCmd.command("unfold <file> <symbol>").description("Show full implementati
7867
9176
  process.exit(1);
7868
9177
  }
7869
9178
  });
9179
+ program.command("audit [path]").description("Audit codebase for code quality, security, and clean architecture standards").option("--fix", "Automatically fix safe violations (e.g. missing direct access guards)").option("--type <type>", "Specify project type (perfex-module, wordpress-plugin, wordpress-theme)").action(async (targetPath, options) => {
9180
+ try {
9181
+ const auditCommand = new AuditCommand();
9182
+ await auditCommand.execute(targetPath || ".", options);
9183
+ } catch (error) {
9184
+ console.error(`Error: ${error.message}`);
9185
+ process.exit(1);
9186
+ }
9187
+ });
9188
+ program.command("create <name>").description("Scaffold a new module, plugin, or theme with clean architecture standards").option("--type <type>", "Project type (perfex-module, wordpress-plugin, wordpress-theme)", "perfex-module").option("--title <title>", "Friendly display title for the project").option("--description <description>", "Project description").option("--out <dir>", "Target output directory").action(async (name, options) => {
9189
+ try {
9190
+ const createCommand = new CreateCommand();
9191
+ await createCommand.execute(name, options);
9192
+ } catch (error) {
9193
+ console.error(`Error: ${error.message}`);
9194
+ process.exit(1);
9195
+ }
9196
+ });
9197
+ program.command("pack [path]").description("Build and package codebase into clean, production-ready .zip archive").option("-o, --out <directory>", "Output directory for the archive (default: ./releases)").option("--name <name>", "Override archive root folder name").option("--version <version>", "Override version tag").option("--no-build", "Skip automatic asset compilation (npm run build)").action(async (targetPath, options) => {
9198
+ try {
9199
+ const packCommand = new PackCommand();
9200
+ await packCommand.execute(targetPath || ".", options);
9201
+ } catch (error) {
9202
+ console.error(`Error: ${error.message}`);
9203
+ process.exit(1);
9204
+ }
9205
+ });
7870
9206
  program.parse();
7871
9207
  //# sourceMappingURL=heraspec.js.map