@codeyam/codeyam-cli 0.1.0-staging.415103 → 0.1.0-staging.44b55c1

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 (320) hide show
  1. package/analyzer-template/.build-info.json +7 -7
  2. package/analyzer-template/log.txt +3 -3
  3. package/analyzer-template/package.json +9 -9
  4. package/analyzer-template/packages/ai/package.json +1 -1
  5. package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +0 -33
  6. package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +13 -7
  7. package/analyzer-template/packages/analyze/src/lib/asts/index.ts +7 -2
  8. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +0 -98
  9. package/analyzer-template/packages/aws/package.json +2 -2
  10. package/analyzer-template/packages/database/package.json +3 -3
  11. package/analyzer-template/packages/database/src/lib/kysely/tables/editorScenariosTable.ts +20 -0
  12. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts +4 -0
  13. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts.map +1 -1
  14. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js +20 -0
  15. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -1
  16. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.d.ts +2 -0
  17. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.d.ts.map +1 -1
  18. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.js +2 -0
  19. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.js.map +1 -1
  20. package/analyzer-template/packages/github/package.json +1 -1
  21. package/analyzer-template/packages/types/src/enums/ProjectFramework.ts +2 -0
  22. package/analyzer-template/packages/ui-components/package.json +1 -1
  23. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.d.ts +2 -0
  24. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.d.ts.map +1 -1
  25. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.js +2 -0
  26. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.js.map +1 -1
  27. package/codeyam-cli/src/__tests__/memory-scripts/filter-session.test.js +196 -0
  28. package/codeyam-cli/src/__tests__/memory-scripts/filter-session.test.js.map +1 -0
  29. package/codeyam-cli/src/__tests__/memory-scripts/read-json-field.test.js +114 -0
  30. package/codeyam-cli/src/__tests__/memory-scripts/read-json-field.test.js.map +1 -0
  31. package/codeyam-cli/src/__tests__/memory-scripts/ripgrep-fallback.test.js +149 -0
  32. package/codeyam-cli/src/__tests__/memory-scripts/ripgrep-fallback.test.js.map +1 -0
  33. package/codeyam-cli/src/commands/default.js +3 -46
  34. package/codeyam-cli/src/commands/default.js.map +1 -1
  35. package/codeyam-cli/src/commands/editor.js +2354 -284
  36. package/codeyam-cli/src/commands/editor.js.map +1 -1
  37. package/codeyam-cli/src/commands/init.js +6 -1
  38. package/codeyam-cli/src/commands/init.js.map +1 -1
  39. package/codeyam-cli/src/data/techStacks.js +77 -0
  40. package/codeyam-cli/src/data/techStacks.js.map +1 -0
  41. package/codeyam-cli/src/utils/__tests__/devServerState.test.js +134 -0
  42. package/codeyam-cli/src/utils/__tests__/devServerState.test.js.map +1 -0
  43. package/codeyam-cli/src/utils/__tests__/editorApi.test.js +127 -0
  44. package/codeyam-cli/src/utils/__tests__/editorApi.test.js.map +1 -0
  45. package/codeyam-cli/src/utils/__tests__/editorAudit.test.js +635 -0
  46. package/codeyam-cli/src/utils/__tests__/editorAudit.test.js.map +1 -0
  47. package/codeyam-cli/src/utils/__tests__/editorCapture.test.js +93 -0
  48. package/codeyam-cli/src/utils/__tests__/editorCapture.test.js.map +1 -0
  49. package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js +304 -0
  50. package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js.map +1 -0
  51. package/codeyam-cli/src/utils/__tests__/editorEntityChangeStatus.test.js +121 -0
  52. package/codeyam-cli/src/utils/__tests__/editorEntityChangeStatus.test.js.map +1 -0
  53. package/codeyam-cli/src/utils/__tests__/editorImageVerifier.test.js +294 -0
  54. package/codeyam-cli/src/utils/__tests__/editorImageVerifier.test.js.map +1 -0
  55. package/codeyam-cli/src/utils/__tests__/editorJournal.test.js +542 -0
  56. package/codeyam-cli/src/utils/__tests__/editorJournal.test.js.map +1 -0
  57. package/codeyam-cli/src/utils/__tests__/editorLoaderHelpers.test.js +393 -0
  58. package/codeyam-cli/src/utils/__tests__/editorLoaderHelpers.test.js.map +1 -0
  59. package/codeyam-cli/src/utils/__tests__/editorMockState.test.js +270 -0
  60. package/codeyam-cli/src/utils/__tests__/editorMockState.test.js.map +1 -0
  61. package/codeyam-cli/src/utils/__tests__/editorPreloadHelpers.test.js +217 -0
  62. package/codeyam-cli/src/utils/__tests__/editorPreloadHelpers.test.js.map +1 -0
  63. package/codeyam-cli/src/utils/__tests__/editorPreview.test.js +266 -0
  64. package/codeyam-cli/src/utils/__tests__/editorPreview.test.js.map +1 -0
  65. package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js +107 -0
  66. package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js.map +1 -0
  67. package/codeyam-cli/src/utils/__tests__/editorScenarioLookup.test.js +139 -0
  68. package/codeyam-cli/src/utils/__tests__/editorScenarioLookup.test.js.map +1 -0
  69. package/codeyam-cli/src/utils/__tests__/editorScenarioSwitch.test.js +221 -0
  70. package/codeyam-cli/src/utils/__tests__/editorScenarioSwitch.test.js.map +1 -0
  71. package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js +221 -0
  72. package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js.map +1 -0
  73. package/codeyam-cli/src/utils/__tests__/editorSeedAdapter.test.js +213 -0
  74. package/codeyam-cli/src/utils/__tests__/editorSeedAdapter.test.js.map +1 -0
  75. package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js +1737 -0
  76. package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js.map +1 -0
  77. package/codeyam-cli/src/utils/__tests__/git.editor.test.js +134 -0
  78. package/codeyam-cli/src/utils/__tests__/git.editor.test.js.map +1 -0
  79. package/codeyam-cli/src/utils/__tests__/journalCaptureStabilization.test.js +107 -0
  80. package/codeyam-cli/src/utils/__tests__/journalCaptureStabilization.test.js.map +1 -0
  81. package/codeyam-cli/src/utils/__tests__/parseRegisterArg.test.js +101 -0
  82. package/codeyam-cli/src/utils/__tests__/parseRegisterArg.test.js.map +1 -0
  83. package/codeyam-cli/src/utils/__tests__/project.test.js +65 -0
  84. package/codeyam-cli/src/utils/__tests__/project.test.js.map +1 -0
  85. package/codeyam-cli/src/utils/__tests__/scenarioMarkers.test.js +121 -0
  86. package/codeyam-cli/src/utils/__tests__/scenarioMarkers.test.js.map +1 -0
  87. package/codeyam-cli/src/utils/__tests__/scenariosManifest.test.js +246 -0
  88. package/codeyam-cli/src/utils/__tests__/scenariosManifest.test.js.map +1 -0
  89. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +25 -5
  90. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  91. package/codeyam-cli/src/utils/__tests__/templateConsistency.test.js +51 -0
  92. package/codeyam-cli/src/utils/__tests__/templateConsistency.test.js.map +1 -0
  93. package/codeyam-cli/src/utils/__tests__/webappDetection.test.js +142 -0
  94. package/codeyam-cli/src/utils/__tests__/webappDetection.test.js.map +1 -0
  95. package/codeyam-cli/src/utils/backgroundServer.js +2 -2
  96. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  97. package/codeyam-cli/src/utils/buildFlags.js +4 -0
  98. package/codeyam-cli/src/utils/buildFlags.js.map +1 -0
  99. package/codeyam-cli/src/utils/devServerState.js +71 -0
  100. package/codeyam-cli/src/utils/devServerState.js.map +1 -0
  101. package/codeyam-cli/src/utils/editorApi.js +73 -0
  102. package/codeyam-cli/src/utils/editorApi.js.map +1 -0
  103. package/codeyam-cli/src/utils/editorAudit.js +159 -0
  104. package/codeyam-cli/src/utils/editorAudit.js.map +1 -0
  105. package/codeyam-cli/src/utils/editorCapture.js +102 -0
  106. package/codeyam-cli/src/utils/editorCapture.js.map +1 -0
  107. package/codeyam-cli/src/utils/editorDevServer.js +197 -0
  108. package/codeyam-cli/src/utils/editorDevServer.js.map +1 -0
  109. package/codeyam-cli/src/utils/editorEntityChangeStatus.js +44 -0
  110. package/codeyam-cli/src/utils/editorEntityChangeStatus.js.map +1 -0
  111. package/codeyam-cli/src/utils/editorImageVerifier.js +155 -0
  112. package/codeyam-cli/src/utils/editorImageVerifier.js.map +1 -0
  113. package/codeyam-cli/src/utils/editorJournal.js +225 -0
  114. package/codeyam-cli/src/utils/editorJournal.js.map +1 -0
  115. package/codeyam-cli/src/utils/editorLoaderHelpers.js +81 -0
  116. package/codeyam-cli/src/utils/editorLoaderHelpers.js.map +1 -0
  117. package/codeyam-cli/src/utils/editorMockState.js +248 -0
  118. package/codeyam-cli/src/utils/editorMockState.js.map +1 -0
  119. package/codeyam-cli/src/utils/editorPreloadHelpers.js +135 -0
  120. package/codeyam-cli/src/utils/editorPreloadHelpers.js.map +1 -0
  121. package/codeyam-cli/src/utils/editorPreview.js +106 -0
  122. package/codeyam-cli/src/utils/editorPreview.js.map +1 -0
  123. package/codeyam-cli/src/utils/editorScenarioSwitch.js +112 -0
  124. package/codeyam-cli/src/utils/editorScenarioSwitch.js.map +1 -0
  125. package/codeyam-cli/src/utils/editorScenarios.js +96 -0
  126. package/codeyam-cli/src/utils/editorScenarios.js.map +1 -0
  127. package/codeyam-cli/src/utils/editorSeedAdapter.js +173 -0
  128. package/codeyam-cli/src/utils/editorSeedAdapter.js.map +1 -0
  129. package/codeyam-cli/src/utils/entityChangeStatus.js +347 -0
  130. package/codeyam-cli/src/utils/entityChangeStatus.js.map +1 -0
  131. package/codeyam-cli/src/utils/entityChangeStatus.server.js +158 -0
  132. package/codeyam-cli/src/utils/entityChangeStatus.server.js.map +1 -0
  133. package/codeyam-cli/src/utils/git.js +51 -0
  134. package/codeyam-cli/src/utils/git.js.map +1 -1
  135. package/codeyam-cli/src/utils/install-skills.js +28 -17
  136. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  137. package/codeyam-cli/src/utils/parseRegisterArg.js +31 -0
  138. package/codeyam-cli/src/utils/parseRegisterArg.js.map +1 -0
  139. package/codeyam-cli/src/utils/project.js +15 -5
  140. package/codeyam-cli/src/utils/project.js.map +1 -1
  141. package/codeyam-cli/src/utils/scenarioMarkers.js +134 -0
  142. package/codeyam-cli/src/utils/scenarioMarkers.js.map +1 -0
  143. package/codeyam-cli/src/utils/scenariosManifest.js +112 -0
  144. package/codeyam-cli/src/utils/scenariosManifest.js.map +1 -0
  145. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +46 -16
  146. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  147. package/codeyam-cli/src/utils/testRunner.js +1 -1
  148. package/codeyam-cli/src/utils/testRunner.js.map +1 -1
  149. package/codeyam-cli/src/utils/webappDetection.js +21 -0
  150. package/codeyam-cli/src/utils/webappDetection.js.map +1 -1
  151. package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js +410 -0
  152. package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js.map +1 -0
  153. package/codeyam-cli/src/webserver/app/lib/database.js +41 -27
  154. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  155. package/codeyam-cli/src/webserver/app/lib/git.js +396 -0
  156. package/codeyam-cli/src/webserver/app/lib/git.js.map +1 -0
  157. package/codeyam-cli/src/webserver/build/client/assets/{CopyButton-DmJveP3T.js → CopyButton-BPXZwM4t.js} +1 -1
  158. package/codeyam-cli/src/webserver/build/client/assets/{EntityItem-C76mRRiF.js → EntityItem-BcgbViKV.js} +3 -3
  159. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeIcon-CobE682z.js → EntityTypeIcon-CQIG2qda.js} +9 -9
  160. package/codeyam-cli/src/webserver/build/client/assets/{ReportIssueModal-djPLI-WV.js → ReportIssueModal-BzHcG7SE.js} +3 -3
  161. package/codeyam-cli/src/webserver/build/client/assets/{ScenarioViewer-B76aig_2.js → ScenarioViewer-0DY_NKil.js} +3 -3
  162. package/codeyam-cli/src/webserver/build/client/assets/ViewportInspectBar-oAf2Kqsf.js +1 -0
  163. package/codeyam-cli/src/webserver/build/client/assets/{_index-C96V0n15.js → _index-DLxKhri3.js} +3 -3
  164. package/codeyam-cli/src/webserver/build/client/assets/{activity.(_tab)-BpKzcsJz.js → activity.(_tab)-BcY3q6nt.js} +6 -6
  165. package/codeyam-cli/src/webserver/build/client/assets/addon-canvas-DpzMmAy5.js +1 -0
  166. package/codeyam-cli/src/webserver/build/client/assets/addon-fit-YJmn1quW.js +12 -0
  167. package/codeyam-cli/src/webserver/build/client/assets/addon-webgl-DI8QOUvO.js +58 -0
  168. package/codeyam-cli/src/webserver/build/client/assets/{agent-transcripts-D9hemwl6.js → agent-transcripts-Bni3iiUj.js} +5 -5
  169. package/codeyam-cli/src/webserver/build/client/assets/api.editor-audit-l0sNRNKZ.js +1 -0
  170. package/codeyam-cli/src/webserver/build/client/assets/api.editor-file-diff-l0sNRNKZ.js +1 -0
  171. package/codeyam-cli/src/webserver/build/client/assets/api.editor-file-l0sNRNKZ.js +1 -0
  172. package/codeyam-cli/src/webserver/build/client/assets/api.editor-load-commit-l0sNRNKZ.js +1 -0
  173. package/codeyam-cli/src/webserver/build/client/assets/api.editor-project-info-l0sNRNKZ.js +1 -0
  174. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenarios-l0sNRNKZ.js +1 -0
  175. package/codeyam-cli/src/webserver/build/client/assets/{book-open-D_nMCFmP.js → book-open-BYOypzCa.js} +2 -2
  176. package/codeyam-cli/src/webserver/build/client/assets/{chevron-down-BH2h1Ea2.js → chevron-down-C_Pmso5S.js} +2 -2
  177. package/codeyam-cli/src/webserver/build/client/assets/{circle-check-DyIKORY6.js → circle-check-BVMi9VA5.js} +2 -2
  178. package/codeyam-cli/src/webserver/build/client/assets/{copy-NDbZjXao.js → copy-n2FB0_Sw.js} +3 -3
  179. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CC6AbExI.js +41 -0
  180. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-Csi0_PMl.js +1 -0
  181. package/codeyam-cli/src/webserver/build/client/assets/editor-pyT-NAuu.js +10 -0
  182. package/codeyam-cli/src/webserver/build/client/assets/editorPreview-BLQMSKZa.js +41 -0
  183. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-CrjR3zZW.js → entity._sha._-BF4oLwaE.js} +3 -3
  184. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.dev-C7YX6r3H.js +6 -0
  185. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-CF164ouH.js +6 -0
  186. package/codeyam-cli/src/webserver/build/client/assets/{files-DO4CZ16O.js → files-BZrlFE1F.js} +1 -1
  187. package/codeyam-cli/src/webserver/build/client/assets/git-DdZcvjGh.js +1 -0
  188. package/codeyam-cli/src/webserver/build/client/assets/globals-BkWJ_UNc.css +1 -0
  189. package/codeyam-cli/src/webserver/build/client/assets/index-yHOVb4rc.js +15 -0
  190. package/codeyam-cli/src/webserver/build/client/assets/{loader-circle-BAXYRVEO.js → loader-circle-DaAZ_H2w.js} +2 -2
  191. package/codeyam-cli/src/webserver/build/client/assets/manifest-753dd058.js +1 -0
  192. package/codeyam-cli/src/webserver/build/client/assets/{memory-FweZHj5U.js → memory-Bl2rpw8u.js} +13 -10
  193. package/codeyam-cli/src/webserver/build/client/assets/{pause-DTAcYxBt.js → pause-f5-1lKBt.js} +3 -3
  194. package/codeyam-cli/src/webserver/build/client/assets/{root-Dzn8nIkU.js → root-B_X8HS1x.js} +15 -15
  195. package/codeyam-cli/src/webserver/build/client/assets/{search-fKo7v0Zo.js → search-Di64LWVb.js} +2 -2
  196. package/codeyam-cli/src/webserver/build/client/assets/{settings-DfuTtcJP.js → settings-0OrEMU6J.js} +1 -1
  197. package/codeyam-cli/src/webserver/build/client/assets/{simulations-B3aOzpCZ.js → simulations-DWT-CvLy.js} +1 -1
  198. package/codeyam-cli/src/webserver/build/client/assets/{terminal-BG4heKCG.js → terminal-Br7MOqts.js} +3 -3
  199. package/codeyam-cli/src/webserver/build/client/assets/{triangle-alert-DtSmdtM4.js → triangle-alert-BLdiCuG-.js} +2 -2
  200. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-CrAK28Bc.js +1 -0
  201. package/codeyam-cli/src/webserver/build/client/assets/xterm-BqvuqXEL.js +27 -0
  202. package/codeyam-cli/src/webserver/build/server/assets/{index-DeSuKbSF.js → index-Dp5Hp9wV.js} +1 -1
  203. package/codeyam-cli/src/webserver/build/server/assets/server-build-DpDPLKrh.js +416 -0
  204. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  205. package/codeyam-cli/src/webserver/build-info.json +5 -5
  206. package/codeyam-cli/src/webserver/editorProxy.js +557 -50
  207. package/codeyam-cli/src/webserver/editorProxy.js.map +1 -1
  208. package/codeyam-cli/src/webserver/scripts/codeyam-preload.mjs +414 -0
  209. package/codeyam-cli/src/webserver/scripts/journalCapture.ts +118 -9
  210. package/codeyam-cli/src/webserver/server.js +93 -12
  211. package/codeyam-cli/src/webserver/server.js.map +1 -1
  212. package/codeyam-cli/src/webserver/terminalServer.js +131 -11
  213. package/codeyam-cli/src/webserver/terminalServer.js.map +1 -1
  214. package/codeyam-cli/templates/chrome-extension-react/EXTENSION_SETUP.md +75 -0
  215. package/codeyam-cli/templates/chrome-extension-react/gitignore +15 -0
  216. package/codeyam-cli/templates/chrome-extension-react/index.html +12 -0
  217. package/codeyam-cli/templates/chrome-extension-react/package.json +26 -0
  218. package/codeyam-cli/templates/chrome-extension-react/popup.html +12 -0
  219. package/codeyam-cli/templates/chrome-extension-react/public/manifest.json +15 -0
  220. package/codeyam-cli/templates/chrome-extension-react/src/background/service-worker.ts +7 -0
  221. package/codeyam-cli/templates/chrome-extension-react/src/globals.css +6 -0
  222. package/codeyam-cli/templates/chrome-extension-react/src/lib/storage.ts +37 -0
  223. package/codeyam-cli/templates/chrome-extension-react/src/popup/App.tsx +12 -0
  224. package/codeyam-cli/templates/chrome-extension-react/src/popup/main.tsx +10 -0
  225. package/codeyam-cli/templates/chrome-extension-react/tsconfig.json +24 -0
  226. package/codeyam-cli/templates/chrome-extension-react/vite.config.ts +41 -0
  227. package/codeyam-cli/templates/editor-step-hook.py +108 -20
  228. package/codeyam-cli/templates/expo-react-native/MOBILE_SETUP.md +89 -0
  229. package/codeyam-cli/templates/expo-react-native/app/(tabs)/_layout.tsx +33 -0
  230. package/codeyam-cli/templates/expo-react-native/app/(tabs)/index.tsx +12 -0
  231. package/codeyam-cli/templates/expo-react-native/app/(tabs)/settings.tsx +12 -0
  232. package/codeyam-cli/templates/expo-react-native/app/_layout.tsx +12 -0
  233. package/codeyam-cli/templates/expo-react-native/app.json +18 -0
  234. package/codeyam-cli/templates/expo-react-native/babel.config.js +9 -0
  235. package/codeyam-cli/templates/expo-react-native/gitignore +12 -0
  236. package/codeyam-cli/templates/expo-react-native/global.css +3 -0
  237. package/codeyam-cli/templates/expo-react-native/lib/storage.ts +32 -0
  238. package/codeyam-cli/templates/expo-react-native/metro.config.js +6 -0
  239. package/codeyam-cli/templates/expo-react-native/nativewind-env.d.ts +1 -0
  240. package/codeyam-cli/templates/expo-react-native/package.json +37 -0
  241. package/codeyam-cli/templates/expo-react-native/tailwind.config.js +10 -0
  242. package/codeyam-cli/templates/expo-react-native/tsconfig.json +10 -0
  243. package/codeyam-cli/templates/nextjs-prisma-sqlite/AUTH_PATTERNS.md +308 -0
  244. package/codeyam-cli/templates/nextjs-prisma-sqlite/AUTH_UPGRADE.md +304 -0
  245. package/codeyam-cli/templates/nextjs-prisma-sqlite/DATABASE.md +112 -0
  246. package/codeyam-cli/templates/nextjs-prisma-sqlite/FEATURE_PATTERNS.md +37 -0
  247. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/codeyam-isolate/layout.tsx +12 -0
  248. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/lib/prisma.ts +9 -4
  249. package/codeyam-cli/templates/nextjs-prisma-sqlite/env +4 -0
  250. package/codeyam-cli/templates/nextjs-prisma-sqlite/gitignore +64 -0
  251. package/codeyam-cli/templates/nextjs-prisma-sqlite/package.json +4 -1
  252. package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma/seed.ts +4 -1
  253. package/codeyam-cli/templates/nextjs-prisma-sqlite/seed-adapter.ts +92 -0
  254. package/codeyam-cli/templates/nextjs-prisma-sqlite/vitest.config.ts +13 -0
  255. package/codeyam-cli/templates/{nextjs-prisma-sqlite/PRISMA_SETUP.md → nextjs-prisma-supabase/SUPABASE_SETUP.md} +37 -17
  256. package/codeyam-cli/templates/nextjs-prisma-supabase/app/api/todos/route.ts +17 -0
  257. package/codeyam-cli/templates/nextjs-prisma-supabase/app/globals.css +26 -0
  258. package/codeyam-cli/templates/nextjs-prisma-supabase/app/layout.tsx +34 -0
  259. package/codeyam-cli/templates/nextjs-prisma-supabase/app/lib/prisma.ts +20 -0
  260. package/codeyam-cli/templates/nextjs-prisma-supabase/app/lib/supabase.ts +12 -0
  261. package/codeyam-cli/templates/nextjs-prisma-supabase/app/page.tsx +10 -0
  262. package/codeyam-cli/templates/nextjs-prisma-supabase/env +9 -0
  263. package/codeyam-cli/templates/nextjs-prisma-supabase/eslint.config.mjs +11 -0
  264. package/codeyam-cli/templates/nextjs-prisma-supabase/gitignore +40 -0
  265. package/codeyam-cli/templates/nextjs-prisma-supabase/next.config.ts +11 -0
  266. package/codeyam-cli/templates/nextjs-prisma-supabase/package.json +36 -0
  267. package/codeyam-cli/templates/nextjs-prisma-supabase/postcss.config.mjs +7 -0
  268. package/codeyam-cli/templates/nextjs-prisma-supabase/prisma/schema.prisma +27 -0
  269. package/codeyam-cli/templates/nextjs-prisma-supabase/prisma/seed.ts +39 -0
  270. package/codeyam-cli/templates/nextjs-prisma-supabase/prisma.config.ts +12 -0
  271. package/codeyam-cli/templates/nextjs-prisma-supabase/tsconfig.json +34 -0
  272. package/codeyam-cli/templates/{codeyam-dev-mode.md → skills/codeyam-dev-mode/SKILL.md} +2 -2
  273. package/codeyam-cli/templates/skills/codeyam-editor/SKILL.md +145 -0
  274. package/codeyam-cli/templates/{codeyam-memory.md → skills/codeyam-memory/SKILL.md} +215 -0
  275. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/deprecated-prompt.md +100 -0
  276. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/detect-deprecated-patterns.mjs +139 -0
  277. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/find-exports.mjs +52 -0
  278. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/misleading-api-prompt.md +117 -0
  279. package/codeyam-cli/templates/skills/codeyam-memory/scripts/lib/read-json-field.mjs +61 -0
  280. package/codeyam-cli/templates/skills/codeyam-memory/scripts/lib/ripgrep-fallback.mjs +155 -0
  281. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/analyze-prompt.md +46 -0
  282. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/cleanup.mjs +13 -0
  283. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/filter-session.mjs +95 -0
  284. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/preprocess.mjs +160 -0
  285. package/package.json +15 -10
  286. package/packages/ai/src/lib/generateExecutionFlows.js +0 -11
  287. package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -1
  288. package/packages/analyze/src/lib/ProjectAnalyzer.js +10 -4
  289. package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
  290. package/packages/analyze/src/lib/asts/index.js +4 -2
  291. package/packages/analyze/src/lib/asts/index.js.map +1 -1
  292. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +0 -40
  293. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -1
  294. package/packages/database/src/lib/kysely/tables/editorScenariosTable.js +20 -0
  295. package/packages/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -1
  296. package/packages/types/src/enums/ProjectFramework.js +2 -0
  297. package/packages/types/src/enums/ProjectFramework.js.map +1 -1
  298. package/scripts/npm-post-install.cjs +34 -0
  299. package/codeyam-cli/src/webserver/build/client/assets/Terminal-BaIiqg_w.js +0 -41
  300. package/codeyam-cli/src/webserver/build/client/assets/addon-fit-CUXOrorO.js +0 -1
  301. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CMT1jU2q.js +0 -21
  302. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-BiM6z3Do.js +0 -1
  303. package/codeyam-cli/src/webserver/build/client/assets/editor-BaC8lHDG.js +0 -7
  304. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.dev-DloHYjtt.js +0 -6
  305. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-C28BiQzt.js +0 -6
  306. package/codeyam-cli/src/webserver/build/client/assets/git-CFCTYk9I.js +0 -15
  307. package/codeyam-cli/src/webserver/build/client/assets/globals-BH6uYxPM.css +0 -1
  308. package/codeyam-cli/src/webserver/build/client/assets/manifest-fb3128c3.js +0 -1
  309. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-ByhSyh0W.js +0 -1
  310. package/codeyam-cli/src/webserver/build/client/assets/xterm-DMSzMhqy.js +0 -9
  311. package/codeyam-cli/src/webserver/build/server/assets/server-build-BbQ8YBP-.js +0 -362
  312. package/codeyam-cli/templates/codeyam-editor.md +0 -67
  313. package/scripts/finalize-analyzer.cjs +0 -13
  314. /package/codeyam-cli/templates/{codeyam-diagnose.md → commands/codeyam-diagnose.md} +0 -0
  315. /package/codeyam-cli/templates/{codeyam-debug.md → skills/codeyam-debug/SKILL.md} +0 -0
  316. /package/codeyam-cli/templates/{codeyam-new-rule.md → skills/codeyam-new-rule/SKILL.md} +0 -0
  317. /package/codeyam-cli/templates/{codeyam-setup.md → skills/codeyam-setup/SKILL.md} +0 -0
  318. /package/codeyam-cli/templates/{codeyam-sim.md → skills/codeyam-sim/SKILL.md} +0 -0
  319. /package/codeyam-cli/templates/{codeyam-test.md → skills/codeyam-test/SKILL.md} +0 -0
  320. /package/codeyam-cli/templates/{codeyam-verify.md → skills/codeyam-verify/SKILL.md} +0 -0
@@ -1,7 +1,25 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
+ import * as os from 'os';
3
4
  import { fileURLToPath } from 'url';
4
5
  import chalk from 'chalk';
6
+ import { runAnalysisForEntities } from "../utils/analysisRunner.js";
7
+ import { error as errorLog, ProgressReporter, withoutSpinner, } from "../utils/progress.js";
8
+ import { initializeEnvironment, requireBranchAndProject, testEnvironment, } from "../utils/database.js";
9
+ import { loadAnalyses, loadEntities, updateProjectMetadata, } from "../../../packages/database/index.js";
10
+ import { IS_INTERNAL_BUILD } from "../utils/buildFlags.js";
11
+ import { startBackgroundServer } from "../utils/backgroundServer.js";
12
+ import { installClaudeCodeSkills } from "../utils/install-skills.js";
13
+ import { setupClaudeCodeSettings } from "../utils/setupClaudeCodeSettings.js";
14
+ import { getAnalyzerTemplatePath, isAnalyzerFinalized, } from "../utils/analyzer.js";
15
+ import { APP_FORMATS, TECH_STACKS } from "../data/techStacks.js";
16
+ import { getProjectRoot as getStateProjectRoot } from "../state.js";
17
+ import initCommand from "./init.js";
18
+ import { readManifest, syncManifestToDatabase, } from "../utils/scenariosManifest.js";
19
+ import { clearEditorState, clearEditorUserPrompt, } from "../utils/editorScenarios.js";
20
+ import { validateSeedData, detectSeedAdapter, } from "../utils/editorSeedAdapter.js";
21
+ import { buildEditorApiRequest, callEditorApi, EDITOR_API_SUBCOMMANDS, } from "../utils/editorApi.js";
22
+ import { parseRegisterArg } from "../utils/parseRegisterArg.js";
5
23
  const __filename = fileURLToPath(import.meta.url);
6
24
  const __dirname = path.dirname(__filename);
7
25
  const STEP_LABELS = {
@@ -9,12 +27,15 @@ const STEP_LABELS = {
9
27
  2: 'Prototype',
10
28
  3: 'Confirm',
11
29
  4: 'Deconstruct',
12
- 5: 'Glossary',
13
- 6: 'Analyze',
14
- 7: 'App Scenarios',
15
- 8: 'User Scenarios',
16
- 9: 'Verify',
17
- 10: 'Review',
30
+ 5: 'Extract',
31
+ 6: 'Glossary',
32
+ 7: 'Analyze',
33
+ 8: 'App Scenarios',
34
+ 9: 'User Scenarios',
35
+ 10: 'Verify',
36
+ 11: 'Journal',
37
+ 12: 'Review',
38
+ 13: 'Present',
18
39
  };
19
40
  /**
20
41
  * Append a JSONL log entry to .codeyam/logs/editor-log.jsonl
@@ -71,15 +92,11 @@ function writeState(root, state) {
71
92
  }
72
93
  /**
73
94
  * Clear the editor state (for starting a new feature).
95
+ * Does NOT clear the user prompt file — that's handled separately
96
+ * via clearEditorUserPrompt when the previous feature commits.
74
97
  */
75
98
  function clearState(root) {
76
- const statePath = getStatePath(root);
77
- try {
78
- fs.unlinkSync(statePath);
79
- }
80
- catch {
81
- // File doesn't exist, that's fine
82
- }
99
+ clearEditorState(root);
83
100
  }
84
101
  /**
85
102
  * Check if a project has been scaffolded (package.json exists).
@@ -114,13 +131,13 @@ function stepHeader(step, title, feature) {
114
131
  console.log();
115
132
  }
116
133
  /**
117
- * Print a colored progress tracker showing all 10 steps.
134
+ * Print a colored progress tracker showing all 13 steps.
118
135
  * Steps before `current` are green ✓, `current` is bold cyan →, future steps are dim ○.
119
136
  */
120
137
  function printProgressTracker(current) {
121
138
  console.log();
122
139
  console.log(chalk.dim('┌─────────────────────────────────────┐'));
123
- for (let i = 1; i <= 10; i++) {
140
+ for (let i = 1; i <= 13; i++) {
124
141
  const label = STEP_LABELS[i];
125
142
  const num = i < 10 ? ` ${i}` : `${i}`;
126
143
  const content = `${num}. ${label.padEnd(28)}`;
@@ -140,14 +157,13 @@ function printProgressTracker(current) {
140
157
  * Print a hard STOP gate directing to the next command.
141
158
  *
142
159
  * Options:
143
- * - confirm: true → step requires user confirmation before proceeding (steps 1, 3, 9)
160
+ * - confirm: true → step requires user confirmation before proceeding (steps 1, 3, 11)
144
161
  */
145
162
  function stopGate(current, opts) {
146
163
  console.log();
147
164
  console.log(chalk.bold.red('━━━ STOP ━━━'));
148
165
  console.log();
149
- console.log(chalk.red('Complete ALL checklist items above before proceeding.'));
150
- console.log(chalk.red('Do NOT skip ahead. Do NOT combine steps.'));
166
+ console.log(chalk.red('Complete each checklist item above before proceeding to the next step.'));
151
167
  if (opts?.confirm) {
152
168
  console.log();
153
169
  console.log(chalk.yellow('Wait for user confirmation before moving on.'));
@@ -159,7 +175,7 @@ function stopGate(current, opts) {
159
175
  console.log(chalk.yellow('For the CURRENT step (→), show each checklist item with ✓ (done) or ✗ (skipped + reason).'));
160
176
  console.log(chalk.yellow('If any items are ✗, explain why and ask if the user wants to address them.'));
161
177
  console.log();
162
- if (current < 10) {
178
+ if (current < 13) {
163
179
  console.log(chalk.green('When done, run: ') +
164
180
  chalk.bold(`codeyam editor ${current + 1}`));
165
181
  }
@@ -170,6 +186,218 @@ function stopGate(current, opts) {
170
186
  }
171
187
  console.log();
172
188
  }
189
+ /**
190
+ * Print a RESUMING header with step-specific investigation instructions.
191
+ * Called when a step is re-entered (prevState.step === current step).
192
+ */
193
+ function printResumptionHeader(step) {
194
+ const port = getServerPort();
195
+ const checks = {
196
+ 1: [
197
+ 'Check if plan was already written to context file:\n `cat .codeyam/editor-mode-context.md`',
198
+ ],
199
+ 2: ['Check if project files already exist:\n `ls package.json src/`'],
200
+ 3: ['This is a confirmation step — just re-present to user'],
201
+ 4: [
202
+ 'Check if extraction plan already exists in context file:\n `cat .codeyam/editor-mode-context.md`',
203
+ ],
204
+ 5: [
205
+ 'Check if components/functions already extracted:\n `ls src/components/ src/lib/`',
206
+ ],
207
+ 6: [
208
+ 'Check if glossary already populated:\n `cat .codeyam/glossary.json`',
209
+ ],
210
+ 7: ['Check if isolation routes and registered scenarios already exist'],
211
+ 8: ['Check existing scenarios:\n `codeyam editor scenarios`'],
212
+ 9: [
213
+ 'Check existing user-persona scenarios:\n `codeyam editor scenarios`',
214
+ ],
215
+ 10: ['Re-verify is safe to repeat — just re-run the checks'],
216
+ 11: [
217
+ 'Check if a journal entry already exists for this feature:\n `codeyam editor journal-list`',
218
+ 'If an entry exists, use PATCH to update it — do NOT create a new one',
219
+ ],
220
+ 12: ['Re-verify is safe to repeat — just re-run the checks'],
221
+ 13: ['Check if commit already made:\n `git log --oneline -3`'],
222
+ };
223
+ const label = STEP_LABELS[step] || 'Unknown';
224
+ console.log(chalk.bold.yellow(`━━━ RESUMING Step ${step}: ${label} ━━━`));
225
+ console.log(chalk.yellow('This step was already started. Before repeating any actions, investigate:'));
226
+ const items = checks[step] || [];
227
+ for (const item of items) {
228
+ checkbox(item);
229
+ }
230
+ console.log();
231
+ }
232
+ function captureOutput(fn) {
233
+ const stdoutWrite = process.stdout.write.bind(process.stdout);
234
+ const stderrWrite = process.stderr.write.bind(process.stderr);
235
+ const chunks = [];
236
+ const captureWrite = (chunk, encoding, cb) => {
237
+ const text = typeof chunk === 'string'
238
+ ? chunk
239
+ : chunk instanceof Buffer
240
+ ? chunk.toString(typeof encoding === 'string' ? encoding : undefined)
241
+ : String(chunk);
242
+ chunks.push(text);
243
+ if (typeof encoding === 'function') {
244
+ encoding();
245
+ }
246
+ if (typeof cb === 'function') {
247
+ cb();
248
+ }
249
+ return true;
250
+ };
251
+ process.stdout.write = captureWrite;
252
+ process.stderr.write = captureWrite;
253
+ try {
254
+ fn();
255
+ }
256
+ finally {
257
+ process.stdout.write = stdoutWrite;
258
+ process.stderr.write = stderrWrite;
259
+ }
260
+ return chunks.join('');
261
+ }
262
+ function withTempRoot(hasProject, fn) {
263
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codeyam-editor-debug-'));
264
+ if (hasProject) {
265
+ fs.writeFileSync(path.join(root, 'package.json'), '{"name":"codeyam-editor-debug","private":true}', 'utf8');
266
+ }
267
+ try {
268
+ return fn(root);
269
+ }
270
+ finally {
271
+ try {
272
+ fs.rmSync(root, { recursive: true, force: true });
273
+ }
274
+ catch {
275
+ // Best-effort cleanup
276
+ }
277
+ }
278
+ }
279
+ function makeState(step, feature) {
280
+ const now = new Date().toISOString();
281
+ return {
282
+ feature,
283
+ step,
284
+ label: STEP_LABELS[step],
285
+ startedAt: now,
286
+ featureStartedAt: now,
287
+ };
288
+ }
289
+ function normalizeDebugTarget(raw) {
290
+ const value = raw.trim().toLowerCase();
291
+ if (!value)
292
+ return '';
293
+ if (value === 'setup')
294
+ return 'setup';
295
+ if (value === 'overview')
296
+ return 'overview';
297
+ if (value === 'overview-with-state' || value === 'overview-state') {
298
+ return 'overview-with-state';
299
+ }
300
+ if (/^\d+$/.test(value)) {
301
+ return `step-${value}`;
302
+ }
303
+ if (/^step-?\d+$/.test(value)) {
304
+ const num = value.replace('step', '').replace('-', '');
305
+ return `step-${num}`;
306
+ }
307
+ return value;
308
+ }
309
+ function parseDebugTargets(target) {
310
+ if (!target || target.trim().toLowerCase() === 'all')
311
+ return null;
312
+ const rawTargets = target
313
+ .split(',')
314
+ .map((t) => normalizeDebugTarget(t))
315
+ .filter(Boolean);
316
+ const valid = new Set();
317
+ for (const entry of rawTargets) {
318
+ if (entry === 'setup' ||
319
+ entry === 'overview' ||
320
+ entry === 'overview-with-state') {
321
+ valid.add(entry);
322
+ continue;
323
+ }
324
+ if (entry.startsWith('step-')) {
325
+ const num = parseInt(entry.replace('step-', ''), 10);
326
+ if (!isNaN(num) && num >= 1 && num <= 13) {
327
+ valid.add(`step-${num}`);
328
+ continue;
329
+ }
330
+ }
331
+ throw new Error(`Invalid debug target: "${entry}"`);
332
+ }
333
+ return valid;
334
+ }
335
+ function writeContextSnapshot(root, outDir) {
336
+ const contextDir = path.join(outDir, 'context');
337
+ fs.mkdirSync(contextDir, { recursive: true });
338
+ const entries = [];
339
+ const skillPath = path.join(root, '.claude', 'skills', 'codeyam-editor', 'SKILL.md');
340
+ const skillFallback = path.join(__dirname, '..', '..', 'templates', 'codeyam-editor.md');
341
+ const skillSource = fs.existsSync(skillPath) ? skillPath : skillFallback;
342
+ const skillDest = path.join(contextDir, 'codeyam-editor-skill.md');
343
+ fs.copyFileSync(skillSource, skillDest);
344
+ entries.push({
345
+ label: 'codeyam-editor skill',
346
+ source: skillSource,
347
+ file: path.relative(outDir, skillDest),
348
+ status: fs.existsSync(skillPath) ? 'installed' : 'template',
349
+ });
350
+ const claudePath = path.join(root, 'CLAUDE.md');
351
+ if (fs.existsSync(claudePath)) {
352
+ const dest = path.join(contextDir, 'CLAUDE.md');
353
+ fs.copyFileSync(claudePath, dest);
354
+ entries.push({
355
+ label: 'CLAUDE.md',
356
+ source: claudePath,
357
+ file: path.relative(outDir, dest),
358
+ status: 'project',
359
+ });
360
+ }
361
+ else {
362
+ const fallback = path.join(__dirname, '..', '..', 'templates', 'codeyam-editor-claude.md');
363
+ if (fs.existsSync(fallback)) {
364
+ const dest = path.join(contextDir, 'CLAUDE.md');
365
+ fs.copyFileSync(fallback, dest);
366
+ entries.push({
367
+ label: 'CLAUDE.md',
368
+ source: fallback,
369
+ file: path.relative(outDir, dest),
370
+ status: 'template',
371
+ });
372
+ }
373
+ else {
374
+ entries.push({
375
+ label: 'CLAUDE.md',
376
+ file: path.relative(outDir, path.join(contextDir, 'CLAUDE.md')),
377
+ status: 'missing',
378
+ });
379
+ }
380
+ }
381
+ const contextPath = path.join(root, '.codeyam', 'editor-mode-context.md');
382
+ if (fs.existsSync(contextPath)) {
383
+ const dest = path.join(contextDir, 'editor-mode-context.md');
384
+ fs.copyFileSync(contextPath, dest);
385
+ entries.push({
386
+ label: 'editor-mode-context.md',
387
+ source: contextPath,
388
+ file: path.relative(outDir, dest),
389
+ status: 'project',
390
+ });
391
+ }
392
+ else {
393
+ entries.push({
394
+ label: 'editor-mode-context.md',
395
+ file: path.relative(outDir, path.join(contextDir, 'editor-mode-context.md')),
396
+ status: 'missing',
397
+ });
398
+ }
399
+ return entries;
400
+ }
173
401
  // ─── Setup (no args, no project) ──────────────────────────────────────
174
402
  function printSetup(root) {
175
403
  const port = getServerPort();
@@ -177,71 +405,75 @@ function printSetup(root) {
177
405
  console.log();
178
406
  console.log(chalk.bold.cyan('━━━ Editor Mode: Project Setup ━━━'));
179
407
  console.log();
180
- console.log("No project detected. Let's scaffold one.");
408
+ console.log("No project detected. Let's get started.");
181
409
  console.log();
182
- // Resolve the project template directory (works in both src/ and dist/)
183
- const templateDir = path.join(__dirname, '..', '..', 'templates', 'nextjs-prisma-sqlite');
184
- const hasTemplate = fs.existsSync(templateDir);
185
410
  console.log(chalk.bold('Checklist:'));
186
411
  checkbox('Read `.codeyam/editor-mode-context.md` for session state');
187
412
  checkbox('Ask the user what they want to build');
188
- if (hasTemplate) {
189
- checkbox('Copy the project template and install dependencies');
190
- console.log();
191
- console.log(chalk.dim(' Copy template (Next.js + Prisma 7 + SQLite, pre-configured):'));
192
- console.log(chalk.dim(` cp -r ${templateDir}/* .`));
193
- console.log(chalk.dim(` cp ${templateDir}/.env ${templateDir}/.gitignore .`));
194
- console.log(chalk.dim(' npm install'));
195
- console.log();
196
- checkbox('Define your data models in `prisma/schema.prisma`');
197
- console.log(chalk.dim(" Replace the placeholder Todo model with your app's models"));
198
- console.log();
199
- checkbox('Push schema and seed the database');
200
- console.log(chalk.dim(' npm run db:push'));
201
- console.log(chalk.dim(' # Edit prisma/seed.ts with your seed data, then:'));
202
- console.log(chalk.dim(' npm run db:seed'));
203
- console.log();
204
- console.log(chalk.dim(' See PRISMA_SETUP.md for Prisma patterns and important warnings.'));
205
- console.log(chalk.dim(' Key: import { prisma } from "@/app/lib/prisma" in API routes.'));
206
- console.log(chalk.dim(' Key: Seed scripts must use the adapter pattern (see prisma/seed.ts).'));
413
+ console.log();
414
+ // ── App Format Selection ───────────────────────────────────────────
415
+ console.log(chalk.bold('App Format Selection:'));
416
+ console.log(chalk.dim(' After the user describes their project, ask which app formats they want to target.'));
417
+ console.log(chalk.dim(' Use AskUserQuestion with CHECKBOXES (multiple selections allowed):'));
418
+ console.log();
419
+ for (const format of APP_FORMATS) {
420
+ console.log(chalk.yellow(` [ ] ${format.label}`) +
421
+ chalk.dim(` ${format.description}`));
207
422
  }
208
- else {
209
- checkbox('Scaffold the project (Next.js recommended) using temp-dir-rsync pattern');
210
- console.log();
211
- console.log(chalk.dim(' Scaffolding pattern (avoids .claude/ conflicts):'));
212
- console.log(chalk.dim(' SCAFFOLD_DIR="/tmp/codeyam-scaffold-$$" && mkdir -p "$SCAFFOLD_DIR"'));
213
- console.log(chalk.dim(' npx create-next-app@latest "$SCAFFOLD_DIR" --typescript --tailwind --eslint \\'));
214
- console.log(chalk.dim(' --app --no-src-dir --no-import-alias --no-react-compiler --turbopack'));
215
- console.log(chalk.dim(' rsync -a --exclude=\'.git\' "$SCAFFOLD_DIR/" . && rm -rf "$SCAFFOLD_DIR"'));
423
+ console.log();
424
+ // ── Tech Stack Selection ───────────────────────────────────────────
425
+ console.log(chalk.bold('Tech Stack Selection:'));
426
+ console.log(chalk.dim(' Based on the selected formats, present ONLY the matching tech stacks.'));
427
+ console.log(chalk.dim(' A stack matches if ANY of the user\'s selected formats appears in its "Supports" list.'));
428
+ console.log(chalk.dim(' Show ALL matching stacks even if there is only one. Mark the recommended option.'));
429
+ console.log(chalk.dim(' Use AskUserQuestion to let the user pick one.'));
430
+ console.log();
431
+ console.log(chalk.bold(' Available Tech Stacks:'));
432
+ for (const stack of TECH_STACKS) {
433
+ const recommended = stack.recommended ? chalk.green(' (Recommended)') : '';
434
+ const formatLabels = stack.supportedFormats
435
+ .map((f) => APP_FORMATS.find((af) => af.id === f)?.label)
436
+ .join(', ');
437
+ console.log(chalk.bold.yellow(` ${stack.name}`) +
438
+ recommended +
439
+ chalk.dim(` [id: ${stack.id}]`));
440
+ console.log(chalk.dim(` ${stack.description}`));
441
+ console.log(chalk.dim(' Technologies:'));
442
+ for (const tech of stack.technologies) {
443
+ console.log(chalk.dim(` - ${tech}`));
444
+ }
445
+ console.log(chalk.dim(` Supports: ${formatLabels}`));
216
446
  console.log();
217
- checkbox('Set up Prisma + SQLite database');
218
- console.log(chalk.dim(' npm install prisma @prisma/client @prisma/adapter-better-sqlite3 better-sqlite3'));
219
- console.log(chalk.dim(' npm install -D @types/better-sqlite3'));
220
- console.log(chalk.dim(' npx prisma init --datasource-provider sqlite'));
221
- console.log(chalk.dim(' # Define schema, then: npx prisma db push'));
222
447
  }
448
+ console.log(chalk.dim(' If NO stacks match the selected formats, tell the user that support for that format is coming soon'));
449
+ console.log(chalk.dim(' and suggest they pick a supported format for now.'));
223
450
  console.log();
224
- checkbox('Run `codeyam init --force --keep-server` to detect the project and configure it');
225
- console.log(chalk.dim(' This auto-detects webapps and configures the start command for analysis'));
451
+ // ── Default Screen Size Selection ──────────────────────────────────
452
+ console.log(chalk.bold('Default Screen Size:'));
453
+ console.log(chalk.dim(' After selecting a tech stack, ask the user to choose the default screen size for previews and captures.'));
454
+ console.log(chalk.dim(' Use AskUserQuestion with RADIO buttons (single selection):'));
226
455
  console.log();
227
- checkbox('Verify `.codeyam/config.json` has `startCommand` in the webapp entry');
228
- console.log(chalk.dim(' Should look like: "startCommand": { "command": "sh", "args": ["-c", "npm run dev -- --port $PORT"] }'));
229
- console.log(chalk.dim(' If missing, add it manually. $PORT is replaced at runtime by the analyzer.'));
456
+ console.log(chalk.yellow(' ( ) Desktop') + chalk.dim(' 1440 × 900'));
457
+ console.log(chalk.yellow(' ( ) Laptop') + chalk.dim(' 1024 × 768'));
458
+ console.log(chalk.yellow(' ( ) Tablet') + chalk.dim(' 768 × 1024'));
459
+ console.log(chalk.yellow(' ( ) Mobile') + chalk.dim(' — 375 × 667'));
460
+ console.log(chalk.yellow(' ( ) Custom') + chalk.dim(' — ask for width × height'));
230
461
  console.log();
231
- checkbox(`Notify CodeYam: \`curl -s -X POST http://localhost:${port}/api/editor-refresh\``);
232
- checkbox('Verify the preview loads in the browser');
462
+ console.log(chalk.dim(' Pre-select based on app format: mobile-responsive-web-app/desktop-app → Desktop, mobile-app → Mobile, chrome-extension Custom (400×600).'));
463
+ console.log(chalk.dim(' If only one obvious choice, confirm it rather than asking.'));
464
+ console.log(chalk.dim(' Save the choice via: curl -s -X POST http://localhost:PORT/api/editor-project-info -H "Content-Type: application/json" -d \'{"defaultScreenSize":{"name":"Desktop","width":1440,"height":900}}\''));
233
465
  console.log();
234
466
  console.log(chalk.bold.red('━━━ STOP ━━━'));
235
467
  console.log();
236
- console.log(chalk.red('Complete ALL checklist items above. Do NOT start building features yet.'));
237
- console.log();
238
- console.log(chalk.bold.yellow('Present a completion checklist to the user:'));
239
- console.log(chalk.yellow('Show each setup checklist item with ✓ (done) or ✗ (skipped + reason).'));
240
- console.log(chalk.yellow('If any items are ✗, explain why and ask if the user wants to address them.'));
468
+ console.log(chalk.red('Ask the user what they want to build, then ask about app formats, then present tech stacks, then choose a default screen size. Then run:'));
241
469
  console.log();
242
- console.log(chalk.green('When setup is complete, run: ') +
243
- chalk.bold('codeyam editor 1') +
244
- chalk.green(' to start your first feature'));
470
+ console.log(chalk.green(' ') +
471
+ chalk.bold('codeyam editor 1 --feature "Feature Name" --app-formats "FORMAT_IDS" --tech-stack "STACK_ID" --prompt "the user\'s original message"'));
472
+ console.log(chalk.dim(' Replace "Feature Name" with a short title for what the user described.'));
473
+ console.log(chalk.dim(' Replace FORMAT_IDS with the comma-separated format IDs the user selected (e.g., "chrome-extension" or "mobile-responsive-web-app").'));
474
+ console.log(chalk.dim(' Replace STACK_ID with the tech stack id shown in [brackets] above (e.g., "nextjs-prisma-sqlite" or "chrome-extension-react").'));
475
+ console.log(chalk.dim(" Pass --prompt with the user's exact original request so it appears in the journal."));
476
+ console.log(chalk.dim(' Step 1 will guide you through planning and getting user confirmation before any code is written.'));
245
477
  console.log();
246
478
  }
247
479
  // ─── Cycle overview (no args, has project) ────────────────────────────
@@ -258,46 +490,93 @@ function printCycleOverview(root, state) {
258
490
  console.log(chalk.dim('Or run ') +
259
491
  chalk.bold('codeyam editor 1') +
260
492
  chalk.dim(' to start a new feature'));
493
+ console.log();
494
+ console.log(chalk.yellow('If the user reports a bug or requests any change, run: ') +
495
+ chalk.bold('codeyam editor change'));
496
+ console.log(chalk.yellow('This applies even after committing — always use the change workflow.'));
261
497
  }
262
498
  else {
263
- console.log('Each feature follows 10 steps. You MUST run each command in order:');
499
+ console.log('Each feature follows 13 steps. You MUST run each command in order:');
264
500
  console.log();
265
501
  console.log(` ${chalk.bold.yellow(' 1')} ${chalk.bold('Plan')} — Plan the feature, confirm with user`);
266
502
  console.log(` ${chalk.bold.yellow(' 2')} ${chalk.bold('Prototype')} — Build a working prototype fast`);
267
503
  console.log(` ${chalk.bold.yellow(' 3')} ${chalk.bold('Confirm')} — Confirm prototype with user`);
268
- console.log(` ${chalk.bold.yellow(' 4')} ${chalk.bold('Deconstruct')} — TDD extraction into small functions`);
269
- console.log(` ${chalk.bold.yellow(' 5')} ${chalk.bold('Glossary')} Record functions in glossary`);
270
- console.log(` ${chalk.bold.yellow(' 6')} ${chalk.bold('Analyze')} Analyze and verify components`);
271
- console.log(` ${chalk.bold.yellow(' 7')} ${chalk.bold('App Scenarios')} Create app-level scenarios`);
272
- console.log(` ${chalk.bold.yellow(' 8')} ${chalk.bold('User Scenarios')} — Create user-persona scenarios`);
273
- console.log(` ${chalk.bold.yellow(' 9')} ${chalk.bold('Verify')} Review screenshots, check for errors`);
274
- console.log(` ${chalk.bold.yellow('10')} ${chalk.bold('Review')} — Present summary, get approval`);
504
+ console.log(` ${chalk.bold.yellow(' 4')} ${chalk.bold('Deconstruct')} — Read code, plan all extractions`);
505
+ console.log(` ${chalk.bold.yellow(' 5')} ${chalk.bold('Extract')} TDD extraction of functions + components`);
506
+ console.log(` ${chalk.bold.yellow(' 6')} ${chalk.bold('Glossary')} Record functions in glossary`);
507
+ console.log(` ${chalk.bold.yellow(' 7')} ${chalk.bold('Analyze')} Analyze and verify components`);
508
+ console.log(` ${chalk.bold.yellow(' 8')} ${chalk.bold('App Scenarios')} — Create app-level scenarios`);
509
+ console.log(` ${chalk.bold.yellow(' 9')} ${chalk.bold('User Scenarios')} Create user-persona scenarios`);
510
+ console.log(` ${chalk.bold.yellow('10')} ${chalk.bold('Verify')} — Review screenshots, check for errors`);
511
+ console.log(` ${chalk.bold.yellow('11')} ${chalk.bold('Journal')} — Create/update journal entry`);
512
+ console.log(` ${chalk.bold.yellow('12')} ${chalk.bold('Review')} — Verify screenshots and audit`);
513
+ console.log(` ${chalk.bold.yellow('13')} ${chalk.bold('Present')} — Present summary, get approval`);
275
514
  console.log();
276
515
  console.log(chalk.green('Start now: ') + chalk.bold('codeyam editor 1'));
516
+ console.log(chalk.dim(' If the user already described what they want, pass it: codeyam editor 1 --prompt "their message"'));
277
517
  }
278
518
  console.log();
279
519
  }
280
520
  // ─── Step 1: Plan ─────────────────────────────────────────────────────
281
- function printStep1(root) {
282
- clearState(root);
283
- logEvent(root, 'step', { step: 1, label: 'Plan' });
284
- stepHeader(1, 'Plan');
521
+ function printStep1(root, feature, options, userPrompt) {
522
+ const port = getServerPort();
523
+ const prevState = readState(root);
524
+ const isResuming = prevState?.step === 1;
525
+ if (!isResuming) {
526
+ clearState(root);
527
+ }
528
+ // If feature is provided, save initial state so step 2 can pick it up
529
+ if (feature) {
530
+ const now = new Date().toISOString();
531
+ writeState(root, {
532
+ feature,
533
+ step: 1,
534
+ label: STEP_LABELS[1],
535
+ startedAt: isResuming ? prevState.startedAt : now,
536
+ featureStartedAt: isResuming ? prevState.featureStartedAt : now,
537
+ appFormats: options?.appFormats || prevState?.appFormats,
538
+ techStackId: options?.techStackId || prevState?.techStackId,
539
+ });
540
+ }
541
+ // Save the user's original prompt to a separate file
542
+ if (userPrompt) {
543
+ const promptPath = path.join(root, '.codeyam', 'editor-user-prompt.txt');
544
+ fs.mkdirSync(path.dirname(promptPath), { recursive: true });
545
+ fs.writeFileSync(promptPath, userPrompt, 'utf8');
546
+ }
547
+ logEvent(root, 'step', { step: 1, label: 'Plan', feature });
548
+ stepHeader(1, 'Plan', feature);
549
+ if (isResuming) {
550
+ printResumptionHeader(1);
551
+ }
285
552
  console.log('Plan the feature before writing ANY code.');
286
553
  console.log();
287
554
  console.log(chalk.bold('Checklist:'));
288
555
  checkbox('Read `.codeyam/glossary.json` for reusable functions/components');
289
- checkbox('Ask the user what they want to build');
290
- checkbox('Identify the data model (what API routes will return)');
291
- checkbox('Identify the components needed (reuse from glossary where possible)');
292
- checkbox('Identify demo/seed data for the prototype');
293
- checkbox('Present the plan and wait for user confirmation');
294
- console.log();
295
- console.log(chalk.dim('Do NOT write any code during this step. Plan only.'));
556
+ checkbox('Ask the user what they want to build (if not already described)');
557
+ checkbox('Ask clarifying questions using `AskUserQuestion` with selectable options');
558
+ console.log(chalk.dim(' Use AskUserQuestion for EVERY clarifying question give 2-4 concrete options the user can pick from.'));
559
+ console.log(chalk.dim(' Focus on what the USER will see and do, not on databases, APIs, or components.'));
560
+ console.log(chalk.dim(' Do NOT ask about tech stack, frameworks, libraries, or implementation details — only ask about user-facing choices.'));
561
+ console.log(chalk.dim(' Good: "What should happen when there are no results?" → options: "Show empty state message", "Show suggestions"'));
562
+ console.log(chalk.dim(' Bad: Free-form text asking "What do you think about the data model?"'));
563
+ console.log(chalk.dim(' You can ask up to 4 questions at once. Bundle related questions into a single AskUserQuestion call.'));
564
+ checkbox("Summarize what you'll build in plain language the user can verify against their vision");
565
+ checkbox('Set the project title and description for the App tab:');
566
+ console.log(chalk.dim(` curl -s -X POST http://localhost:${port}/api/editor-project-info \\`));
567
+ console.log(chalk.dim(' -H "Content-Type: application/json" \\'));
568
+ console.log(chalk.dim(' -d \'{"projectTitle":"My App","projectDescription":"A short description of what this app does"}\''));
569
+ console.log();
570
+ console.log(chalk.bold('Present a selection menu to the user (use AskUserQuestion with these EXACT option labels):'));
571
+ console.log(chalk.green(' Option 1 label: "This plan is accurate, let\'s prototype it!"') + chalk.dim(' — proceed to step 2'));
572
+ console.log(chalk.yellow(' Option 2 label: "I\'d like some changes"') +
573
+ chalk.dim(' — user describes changes, you revise the plan, then re-present'));
574
+ console.log();
575
+ console.log(chalk.dim('This step is for understanding user goals and getting buy-in. Code comes in Step 2.'));
296
576
  console.log();
297
577
  console.log(chalk.bold.red('━━━ STOP ━━━'));
298
578
  console.log();
299
- console.log(chalk.red('Complete ALL checklist items above before proceeding.'));
300
- console.log(chalk.red('Do NOT skip ahead. Do NOT combine steps.'));
579
+ console.log(chalk.red('Complete each checklist item above before proceeding to the next step.'));
301
580
  console.log();
302
581
  console.log(chalk.yellow('Wait for user confirmation before moving on.'));
303
582
  console.log();
@@ -315,109 +594,274 @@ function printStep1(root) {
315
594
  // ─── Step 2: Prototype ────────────────────────────────────────────────
316
595
  function printStep2(root, feature) {
317
596
  const port = getServerPort();
597
+ const projectExists = hasProject(root);
598
+ const prevState = readState(root);
599
+ const isResuming = prevState?.step === 2;
600
+ const now = new Date().toISOString();
318
601
  writeState(root, {
319
602
  feature,
320
603
  step: 2,
321
604
  label: STEP_LABELS[2],
322
- startedAt: new Date().toISOString(),
605
+ startedAt: isResuming ? prevState.startedAt : now,
606
+ featureStartedAt: isResuming ? prevState.featureStartedAt : now,
607
+ appFormats: prevState?.appFormats,
608
+ techStackId: prevState?.techStackId,
323
609
  });
324
610
  logEvent(root, 'step', { step: 2, label: 'Prototype', feature });
325
611
  stepHeader(2, 'Prototype', feature);
612
+ if (isResuming) {
613
+ printResumptionHeader(2);
614
+ }
326
615
  console.log('Build fast with real data. Prioritize speed over quality.');
327
616
  console.log();
617
+ // If no project exists yet, include scaffolding instructions first
618
+ if (!projectExists) {
619
+ console.log(chalk.bold('Scaffold the project:'));
620
+ checkbox('Run `codeyam editor template` to scaffold, install dependencies, init git, and configure CodeYam');
621
+ console.log(chalk.dim(' This copies the Next.js + Prisma 7 + SQLite template, runs npm install,'));
622
+ console.log(chalk.dim(' initializes git, runs codeyam init, and refreshes the editor — all in one command.'));
623
+ console.log();
624
+ checkbox('Define your data models in `prisma/schema.prisma`');
625
+ console.log(chalk.dim(" Replace the placeholder Todo model with your app's models"));
626
+ console.log();
627
+ checkbox('Push schema and seed the database');
628
+ console.log(chalk.dim(' npm run db:push'));
629
+ console.log(chalk.dim(' # Edit prisma/seed.ts with your seed data, then:'));
630
+ console.log(chalk.dim(' npm run db:seed'));
631
+ console.log(chalk.dim(` # After re-seeding, restart the dev server to pick up fresh data:`));
632
+ console.log(chalk.dim(` # codeyam editor dev-server '{"action":"restart"}'`));
633
+ console.log();
634
+ console.log(chalk.dim(' See PRISMA_SETUP.md for Prisma patterns and important warnings.'));
635
+ console.log(chalk.dim(' Key: import { prisma } from "@/app/lib/prisma" in API routes.'));
636
+ console.log(chalk.dim(' Key: Seed scripts must use the adapter pattern (see prisma/seed.ts).'));
637
+ console.log();
638
+ console.log(chalk.bold('Build the feature:'));
639
+ }
328
640
  console.log(chalk.bold('Checklist:'));
329
- checkbox('Create/update API routes (real database reads via Prisma)');
641
+ checkbox('Create API routes that read from the database via Prisma');
330
642
  checkbox('Seed the database with demo data');
331
- checkbox('Build the page/feature UI components');
643
+ checkbox('Create `.codeyam/seed-adapter.ts` so CodeYam can seed the database for scenarios');
644
+ console.log(chalk.dim(' The seed adapter reads a JSON file (path passed as CLI arg), wipes tables, inserts rows.'));
645
+ console.log(chalk.dim(" Use the project's own ORM (Prisma, Drizzle, etc.). See template for example."));
646
+ console.log(chalk.dim(' Run with: npx tsx .codeyam/seed-adapter.ts <path-to-seed-data.json>'));
332
647
  checkbox('Verify the dev server shows the changes');
648
+ checkbox('If the feature involves auth, email, payments, or other common patterns: read FEATURE_PATTERNS.md');
649
+ // Responsive design guidance when building a mobile-responsive web app
650
+ if (prevState?.appFormats?.includes('mobile-responsive-web-app')) {
651
+ console.log();
652
+ console.log(chalk.bold.magenta('Responsive Design (mobile-responsive-web-app):'));
653
+ console.log(chalk.magenta(' This app must look great on BOTH desktop AND mobile. It is NOT a mobile-only app.'));
654
+ console.log(chalk.magenta(' Design desktop-first with a full-width layout, then ensure it adapts gracefully to mobile.'));
655
+ console.log(chalk.dim(' Use Tailwind responsive prefixes (sm:, md:, lg:) for layout shifts.'));
656
+ console.log(chalk.dim(' Test at both Desktop (1280×800) and Mobile (390×844) sizes before presenting.'));
657
+ }
658
+ console.log();
659
+ console.log(chalk.bold.cyan('Keep the preview moving:'));
660
+ console.log(chalk.cyan(' The user is watching the preview. Refresh it after each meaningful change:'));
661
+ console.log(chalk.cyan(` codeyam editor preview`));
662
+ console.log(chalk.cyan(' Refresh after: first visible page, adding each UI section, seeding data, styling.'));
663
+ console.log(chalk.cyan(' Aim for 4-8+ refreshes during prototyping — not one big reveal at the end.'));
664
+ console.log(chalk.cyan(' If you build a NEW page (e.g., /drinks/[id]), navigate the preview there:'));
665
+ console.log(chalk.cyan(` codeyam editor preview '{"path":"/drinks/1"}'`));
333
666
  console.log();
334
667
  console.log(chalk.bold('Verify the dev server:'));
335
- console.log(chalk.dim(` # Get dev server URL: curl -s http://localhost:${port}/api/editor-dev-server`));
668
+ console.log(chalk.dim(` # Get dev server URL: codeyam editor dev-server`));
336
669
  console.log(chalk.dim(' # Check page loads: curl -s -o /dev/null -w "%{http_code}" http://localhost:<dev-port>'));
337
670
  console.log(chalk.dim(' # Check API routes: curl -s http://localhost:<dev-port>/api/your-route'));
338
671
  console.log();
339
- console.log(chalk.dim('Do NOT create scenarios or run codeyam analyze. Do NOT refactor.'));
672
+ console.log(chalk.bold('Verify before proceeding:'));
673
+ console.log(chalk.yellow(' Verify everything works before presenting the prototype to the user.'));
674
+ checkbox('Verify the page loads: curl the dev server URL and confirm HTTP 200 (not an error page)');
675
+ checkbox('Verify API routes return valid JSON: curl each route and confirm no error responses');
676
+ checkbox('Check for broken images: `codeyam editor verify-images \'{"paths":["/"], "imageUrls":["url1","url2"]}\'`');
677
+ console.log(chalk.dim(' Pass ALL page paths and ALL image URLs you used in seed data / API responses.'));
678
+ console.log(chalk.dim(' Client-rendered pages need imageUrls — the HTML shell has no images to scan.'));
679
+ console.log(chalk.dim(' Fix or replace any broken image URLs in the seed data before proceeding.'));
680
+ checkbox('Check the dev server terminal output for runtime errors (missing modules, failed imports)');
681
+ checkbox('Verify the live preview renders: `codeyam editor client-errors`');
682
+ console.log(chalk.dim(' If `hasContent=false` or `liveErrors>0`, the preview is broken — fix the issue before proceeding.'));
683
+ console.log(chalk.dim(' The user is looking at the preview — a blank page means something is broken.'));
684
+ console.log(chalk.dim(' If any check fails, fix the issue and re-verify before proceeding.'));
685
+ console.log();
686
+ console.log(chalk.dim('Focus on building the prototype. Scenarios and refactoring happen in later steps.'));
340
687
  stopGate(2);
341
688
  }
342
689
  // ─── Step 3: Confirm ──────────────────────────────────────────────────
343
690
  function printStep3(root, feature) {
691
+ const port = getServerPort();
692
+ const prevState = readState(root);
693
+ const isResuming = prevState?.step === 3;
694
+ const now = new Date().toISOString();
344
695
  writeState(root, {
345
696
  feature,
346
697
  step: 3,
347
698
  label: STEP_LABELS[3],
348
- startedAt: new Date().toISOString(),
699
+ startedAt: isResuming ? prevState.startedAt : now,
700
+ featureStartedAt: prevState?.featureStartedAt || now,
349
701
  });
350
702
  logEvent(root, 'step', { step: 3, label: 'Confirm', feature });
351
703
  stepHeader(3, 'Confirm', feature);
704
+ if (isResuming) {
705
+ printResumptionHeader(3);
706
+ }
352
707
  console.log('Summarize what was built and get user confirmation.');
353
708
  console.log();
354
- console.log(chalk.bold('Checklist:'));
355
- checkbox('Summarize what was built (routes, components, data)');
356
- checkbox('Show the user the current state of the prototype');
709
+ console.log(chalk.bold('Before presenting — verify everything works:'));
710
+ checkbox(`Refresh the preview: \`codeyam editor preview\` — check the \`preview\` field for \`healthy: false\``);
711
+ checkbox('Verify API routes return valid data (curl each route)');
712
+ console.log();
713
+ console.log(chalk.bold.red(' Verify EVERY image loads (this is the #1 source of broken prototypes):'));
714
+ checkbox('Run `codeyam editor verify-images \'{"paths":["/"], "imageUrls":["url1","url2"]}\'`');
715
+ console.log(chalk.dim(' Include ALL page paths and ALL image URLs from seed data / API responses.'));
716
+ console.log(chalk.dim(' Client-rendered pages need imageUrls — the HTML shell has no images.'));
717
+ checkbox('Fix or remove any image that returns non-200 before continuing');
718
+ checkbox('Check for client-side errors: `codeyam editor client-errors`');
719
+ console.log(chalk.dim(' If there are errors, fix the underlying issue before presenting.'));
720
+ checkbox('Verify `hasContent=true` and `liveErrors=0` — do NOT ask the user to confirm if the preview is broken');
357
721
  console.log();
358
- console.log(chalk.bold('Present a selection menu to the user (use AskUserQuestion):'));
359
- console.log(chalk.green(' "Yes, this looks right!"') +
360
- chalk.dim(' proceed to step 4'));
361
- console.log(chalk.yellow(' "I\'d like some changes"') +
722
+ console.log(chalk.bold('Then present to the user:'));
723
+ checkbox('Summarize what was built (routes, components, data)');
724
+ checkbox('Navigate the preview to the feature\'s primary page: `codeyam editor preview \'{"path":"/your-page"}\'`');
725
+ console.log(chalk.dim(' The user needs to SEE the new feature. If you built a new page, navigate there.'));
726
+ console.log(chalk.dim(' If you modified an existing page, refresh the preview to show the changes.'));
727
+ console.log();
728
+ console.log(chalk.bold.cyan('Guide the user through interactive testing:'));
729
+ checkbox('Tell the user: "The preview is fully interactive — click around to test!"');
730
+ checkbox('Prompt the user to try key interactions: forms, navigation, buttons, etc.');
731
+ checkbox('Ask the user: "Does everything work as expected?"');
732
+ console.log();
733
+ console.log(chalk.bold('Present a selection menu to the user (use AskUserQuestion with these EXACT option labels):'));
734
+ console.log(chalk.green(' Option 1 label: "The live preview is displaying what I expected"') + chalk.dim(' — proceed to step 4'));
735
+ console.log(chalk.yellow(' Option 2 label: "I\'d like some changes"') +
362
736
  chalk.dim(' — user describes changes, you make them, then re-present'));
363
737
  console.log();
364
- console.log(chalk.dim('Do NOT refactor or create scenarios until the user approves the prototype.'));
738
+ console.log(chalk.dim('Wait for user approval before moving on. Refactoring and scenarios happen in later steps.'));
365
739
  stopGate(3, { confirm: true });
366
740
  }
367
741
  // ─── Step 4: Deconstruct ──────────────────────────────────────────────
368
742
  function printStep4(root, feature) {
743
+ const prevState = readState(root);
744
+ const isResuming = prevState?.step === 4;
745
+ const now = new Date().toISOString();
369
746
  writeState(root, {
370
747
  feature,
371
748
  step: 4,
372
749
  label: STEP_LABELS[4],
373
- startedAt: new Date().toISOString(),
750
+ startedAt: isResuming ? prevState.startedAt : now,
751
+ featureStartedAt: prevState?.featureStartedAt || now,
374
752
  });
375
753
  logEvent(root, 'step', { step: 4, label: 'Deconstruct', feature });
376
754
  stepHeader(4, 'Deconstruct', feature);
377
- console.log('TDD extraction: write failing tests first, then extract.');
378
- console.log();
379
- console.log(chalk.bold('Checklist:'));
380
- checkbox('Read `.codeyam/glossary.json` reuse existing functions/components where they fit');
381
- checkbox('Review the prototype code for extractable logic');
382
- checkbox('Extract reusable components (each should accept props, render independently)');
383
- checkbox('Extract utility functions (pure functions where possible)');
384
- checkbox('Each component should be small enough to analyze independently');
385
- console.log();
386
- console.log(chalk.bold('Testing — CRITICAL:'));
387
- console.log(chalk.yellow(' Every extracted library function MUST have a dedicated test file'));
388
- console.log(chalk.yellow(' with thorough coverage. `codeyam analyze` only captures screenshots'));
389
- console.log(chalk.yellow(' for visual components — it does NOT test library functions.'));
390
- console.log(chalk.yellow(' Your tests ARE the only test coverage for these functions.'));
391
- console.log();
392
- checkbox('For each extracted function: write MULTIPLE failing tests FIRST, then extract to make them pass');
393
- console.log(chalk.dim(' Cover: typical inputs, edge cases, empty/null inputs, error conditions'));
394
- console.log(chalk.dim(' Aim for 3-8 test cases per function depending on complexity'));
395
- checkbox('Place test files next to source: `app/lib/drinks.ts` → `app/lib/drinks.test.ts`');
396
- checkbox('Run all tests and verify they pass before proceeding');
755
+ if (isResuming) {
756
+ printResumptionHeader(4);
757
+ }
758
+ console.log(chalk.bold('Goal: pages contain ONLY components. Components contain ONLY sub-components.'));
759
+ console.log(chalk.yellow('This step is read and plan only. Code extraction happens in step 5.'));
397
760
  console.log();
398
- console.log(chalk.dim('Reuse glossary functions when they fit naturally — but do NOT overload an existing'));
399
- console.log(chalk.dim('function to handle too many situations. Extract a new one if the use case diverges.'));
761
+ console.log(chalk.bold.red('THE RULE: No direct JSX in page files.'));
762
+ console.log(chalk.yellow(' After extraction, a page/route file should import and compose components nothing else.'));
763
+ console.log(chalk.yellow(' Every distinct visual section in the page is its own component.'));
764
+ console.log(chalk.yellow(' Every component that renders multiple distinct sections should be split into sub-components.'));
765
+ console.log(chalk.yellow(' If a component has N visually distinct parts, it should compose N sub-components.'));
400
766
  console.log();
401
- console.log(chalk.dim('Do NOT create scenarios. Write failing tests first, then extract. TDD only.'));
767
+ console.log(chalk.bold('Checklist:'));
768
+ checkbox('Read `.codeyam/glossary.json` — note reusable functions/components');
769
+ checkbox('Read EVERY file created or modified in this session');
770
+ console.log(chalk.yellow(' For EACH file, identify EVERY extractable piece:'));
771
+ console.log(chalk.yellow(' Components: headers, nav, loading states, empty states, error states,'));
772
+ console.log(chalk.yellow(' badges/pills, image containers, card sections, form fields, modals,'));
773
+ console.log(chalk.yellow(' titles, descriptions, rating displays, status indicators, buttons'));
774
+ console.log(chalk.yellow(' Functions: data transforms, calculations, formatting, validation,'));
775
+ console.log(chalk.yellow(' API response shaping, any logic that is not directly about rendering'));
776
+ console.log(chalk.yellow(' Hooks: data fetching, state management, side effects'));
777
+ console.log();
778
+ checkbox('Write a numbered extraction plan listing EVERYTHING you will extract');
779
+ console.log(chalk.yellow(' The end state: every page file is ONLY imports + component composition.'));
780
+ console.log(chalk.yellow(' No raw <div>, <span>, <h1>, <p>, <img>, or <ul> in page files.'));
781
+ console.log(chalk.yellow(' Every visual section in every component is itself a component.'));
782
+ console.log();
783
+ console.log(chalk.yellow(' For each item in the plan, note:'));
784
+ console.log(chalk.yellow(' — What it is (component, function, hook)'));
785
+ console.log(chalk.yellow(' — Where it currently lives (source file + approximate lines)'));
786
+ console.log(chalk.yellow(' — Where it will go (new file path)'));
787
+ console.log();
788
+ console.log(chalk.dim('Present the numbered plan, then proceed to step 5 to execute it.'));
402
789
  stopGate(4);
403
790
  }
404
- // ─── Step 5: Glossary ─────────────────────────────────────────────────
791
+ // ─── Step 5: Extract ──────────────────────────────────────────────────
405
792
  function printStep5(root, feature) {
793
+ const port = getServerPort();
794
+ const prevState = readState(root);
795
+ const isResuming = prevState?.step === 5;
796
+ const now = new Date().toISOString();
406
797
  writeState(root, {
407
798
  feature,
408
799
  step: 5,
409
800
  label: STEP_LABELS[5],
410
- startedAt: new Date().toISOString(),
801
+ startedAt: isResuming ? prevState.startedAt : now,
802
+ featureStartedAt: prevState?.featureStartedAt || now,
803
+ });
804
+ logEvent(root, 'step', { step: 5, label: 'Extract', feature });
805
+ stepHeader(5, 'Extract', feature);
806
+ if (isResuming) {
807
+ printResumptionHeader(5);
808
+ }
809
+ console.log('Execute your extraction plan from step 4.');
810
+ console.log();
811
+ console.log(chalk.bold('Components:'));
812
+ checkbox('Extract each component from your plan into its own file');
813
+ checkbox('Page/route files must contain ZERO direct JSX — only imported components');
814
+ checkbox('Every component that renders multiple sections must be split into sub-components');
815
+ console.log(chalk.dim(' No tests needed — visual verification happens in step 7'));
816
+ console.log();
817
+ console.log(chalk.bold('Library functions (TDD):'));
818
+ checkbox('For each function: write MULTIPLE failing tests FIRST, then extract to make them pass');
819
+ console.log(chalk.dim(' Cover: typical inputs, edge cases, empty/null inputs, error conditions'));
820
+ console.log(chalk.dim(' Aim for 3-8 test cases per function depending on complexity'));
821
+ checkbox('Place test files next to source: `app/lib/drinks.ts` → `app/lib/drinks.test.ts`');
822
+ console.log(chalk.yellow(' Tests ARE the only coverage for library functions — step 7 only captures component screenshots.'));
823
+ console.log();
824
+ console.log(chalk.bold('Recursive pass:'));
825
+ checkbox('Re-read EVERY new file you just created — extract components from components, functions from functions');
826
+ checkbox('Keep going until every file is a thin shell: just imports and composition');
827
+ console.log(chalk.yellow(' Check: does any file contain raw <div>, <span>, <h1>, <p>, <img>, or <ul>?'));
828
+ console.log(chalk.yellow(' If yes → that JSX section is a component waiting to be extracted.'));
829
+ console.log();
830
+ console.log(chalk.bold('Verify before proceeding:'));
831
+ checkbox('Run all tests and verify they pass');
832
+ checkbox('Page files contain ONLY imports + component composition — no raw HTML tags');
833
+ checkbox('Every component renders ONE thing or composes sub-components — no multi-section JSX');
834
+ checkbox(`Refresh the preview after each batch of extractions: \`codeyam editor preview\``);
835
+ console.log(chalk.dim(' The user should see the preview stay healthy as you refactor — refresh periodically, not just at the end.'));
836
+ console.log(chalk.dim('Reuse glossary functions when they fit naturally. Extract a new function when the use case diverges.'));
837
+ console.log();
838
+ console.log(chalk.dim('Focus on TDD for functions and extraction for components. Scenarios come in later steps.'));
839
+ stopGate(5);
840
+ }
841
+ // ─── Step 6: Glossary ─────────────────────────────────────────────────
842
+ function printStep6(root, feature) {
843
+ const prevState = readState(root);
844
+ const isResuming = prevState?.step === 6;
845
+ const now = new Date().toISOString();
846
+ writeState(root, {
847
+ feature,
848
+ step: 6,
849
+ label: STEP_LABELS[6],
850
+ startedAt: isResuming ? prevState.startedAt : now,
851
+ featureStartedAt: prevState?.featureStartedAt || now,
411
852
  });
412
- logEvent(root, 'step', { step: 5, label: 'Glossary', feature });
413
- stepHeader(5, 'Glossary', feature);
853
+ logEvent(root, 'step', { step: 6, label: 'Glossary', feature });
854
+ stepHeader(6, 'Glossary', feature);
855
+ if (isResuming) {
856
+ printResumptionHeader(6);
857
+ }
414
858
  console.log('Record all new functions/components in `.codeyam/glossary.json`.');
415
859
  console.log();
416
860
  console.log(chalk.bold('Checklist:'));
417
861
  checkbox("Read `.codeyam/glossary.json` (create if it doesn't exist)");
418
- checkbox('Add an entry for each new function/component extracted in step 4');
862
+ checkbox('Add an entry for each new function/component extracted in step 5');
419
863
  checkbox('Each entry should have: name, filePath, description, parameters, returnType, tags, feature');
420
- checkbox('For each function with a test file from step 4, set `testFile` to the relative path');
864
+ checkbox('For each function with a test file from step 5, set `testFile` to the relative path');
421
865
  console.log();
422
866
  console.log(chalk.bold('Entry format:'));
423
867
  console.log(chalk.dim(' { "name": "calculateTotal", "filePath": "app/utils/pricing.ts",'));
@@ -427,232 +871,1852 @@ function printStep5(root, feature) {
427
871
  console.log(chalk.dim(' "testFile": "app/utils/pricing.test.ts",'));
428
872
  console.log(chalk.dim(` "feature": "${feature}", "createdAt": "..." }`));
429
873
  console.log();
430
- console.log(chalk.dim('Do NOT write application code or create scenarios. Update the glossary only.'));
431
- stopGate(5);
874
+ console.log(chalk.dim('Focus on updating the glossary. Application code and scenarios come in later steps.'));
875
+ stopGate(6);
432
876
  }
433
- // ─── Step 6: Analyze ──────────────────────────────────────────────────
434
- function printStep6(root, feature) {
877
+ // ─── Step 7: Analyze ──────────────────────────────────────────────────
878
+ function printStep7(root, feature) {
879
+ const port = getServerPort();
880
+ const prevState = readState(root);
881
+ const isResuming = prevState?.step === 7;
882
+ const now = new Date().toISOString();
435
883
  writeState(root, {
436
884
  feature,
437
- step: 6,
438
- label: STEP_LABELS[6],
439
- startedAt: new Date().toISOString(),
885
+ step: 7,
886
+ label: STEP_LABELS[7],
887
+ startedAt: isResuming ? prevState.startedAt : now,
888
+ featureStartedAt: prevState?.featureStartedAt || now,
440
889
  });
441
- logEvent(root, 'step', { step: 6, label: 'Analyze', feature });
442
- stepHeader(6, 'Analyze and Verify', feature);
443
- console.log('Verify both visual components (via `codeyam analyze`) and library functions (via tests).');
444
- console.log();
445
- console.log(chalk.bold('Visual Components — `codeyam analyze`:'));
446
- checkbox('List all files with new/modified visual components from step 4');
447
- checkbox('Run ONE `codeyam analyze --noOpen` command with all component files');
448
- console.log(chalk.dim(' Example: codeyam analyze --noOpen app/components/DrinkCard.tsx app/components/StarRating.tsx'));
449
- console.log(chalk.dim(' This discovers and analyzes all entities in all listed files in one pass'));
450
- console.log(chalk.dim(' Use --entity to filter specific entities: --entity DrinkCard --entity StarRating'));
451
- checkbox('Wait for the analyze command to complete');
452
- checkbox('Check results if any failed, read the log and fix the source code');
453
- console.log(chalk.dim(' Log location: /tmp/codeyam/local-dev/<project-slug>/codeyam/log.txt'));
454
- checkbox('Re-run `codeyam analyze` on fixed files until all pass');
890
+ logEvent(root, 'step', { step: 7, label: 'Analyze', feature });
891
+ stepHeader(7, 'Analyze and Verify', feature);
892
+ if (isResuming) {
893
+ printResumptionHeader(7);
894
+ }
895
+ console.log('Verify visual components (via isolation routes) and library functions (via tests).');
896
+ console.log();
897
+ console.log(chalk.bold('Visual Components Component Isolation:'));
898
+ checkbox('List all files with new/modified visual components from step 5');
899
+ checkbox('Create isolation route dirs: `codeyam editor isolate ComponentA ComponentB ...`');
900
+ console.log(chalk.dim(' This creates app/isolated-components/layout.tsx (with production notFound() guard) and'));
901
+ console.log(chalk.dim(' a directory per component. List ALL components that need isolation routes.'));
902
+ checkbox('Check existing scenarios: `codeyam editor scenarios`');
903
+ console.log(chalk.dim(' Reuse and improve existing scenarios where possible update mock data'));
904
+ console.log(chalk.dim(' to reflect current changes. Add new scenarios only for genuinely new states.'));
905
+ console.log(chalk.dim(' Ensure at least one scenario clearly demonstrates what changed in this session.'));
906
+ checkbox('For each visual component:');
907
+ console.log(chalk.dim(' 1. Read the source AND find where it is used in the app to understand:'));
908
+ console.log(chalk.dim(' — Props/interface'));
909
+ console.log(chalk.dim(' — Container width in the real app (e.g. card in a 3-col grid → max-w-sm)'));
910
+ console.log(chalk.dim(' 2. Plan multiple scenarios that exercise the component like tests:'));
911
+ console.log(chalk.dim(' — Default/happy path with typical data'));
912
+ console.log(chalk.dim(' — Edge cases: empty/missing data, long text, maximum items, zero counts'));
913
+ console.log(chalk.dim(' — Different visual states: loading, error, disabled, selected, hover'));
914
+ console.log(chalk.dim(' — Boundary values: single item vs many, min/max ratings, very long names'));
915
+ console.log(chalk.dim(' 3. Create ONE isolation route per component with a scenarios map and ?s= query param:'));
916
+ console.log(chalk.dim(' Remix: app/routes/isolated-components.ComponentName.tsx → /isolated-components/ComponentName'));
917
+ console.log(chalk.dim(' Next.js: app/isolated-components/ComponentName/page.tsx → /isolated-components/ComponentName'));
918
+ console.log(chalk.dim(' The route defines a `scenarios` object mapping scenario names to props,'));
919
+ console.log(chalk.dim(' reads `?s=ScenarioName` from the URL, and renders the component with those props.'));
920
+ console.log(chalk.dim(' Wrap the component in a capture container with id="codeyam-capture":'));
921
+ console.log(chalk.dim(' <div id="codeyam-capture" style={{ display:"inline-block", padding:"20px" }}>'));
922
+ console.log(chalk.dim(' <div style={{ width:"100%", maxWidth:"..." }}> ← match the app\'s container width'));
923
+ console.log(chalk.dim(' e.g. card in a 3-col grid → maxWidth:"24rem", full-width component → omit maxWidth'));
924
+ console.log(chalk.dim(' The screenshot captures just this wrapper, so the component fills the image.'));
925
+ console.log(chalk.dim(' Center the wrapper on the page (flexbox center both axes) and set a page background'));
926
+ console.log(chalk.dim(' color that matches where the component normally appears (e.g. white for light UIs).'));
927
+ console.log(chalk.dim(' 4. Wait 2 seconds for HMR, then register + capture each scenario:'));
928
+ console.log(chalk.dim(` codeyam editor register '{"name":"ComponentName - Scenario",`));
929
+ console.log(chalk.dim(` "componentName":"ComponentName","componentPath":"path/to/file.tsx",`));
930
+ console.log(chalk.dim(` "url":"/isolated-components/ComponentName?s=Scenario",`));
931
+ console.log(chalk.dim(` "mockData":{"routes":{"/api/...":{"body":[...]}}}}'`));
932
+ console.log(chalk.dim(' Optional: add "viewportWidth" and "viewportHeight" to override the project default screen size'));
933
+ console.log(chalk.dim(' If omitted, captures use the project default from setup. Only override for scenarios that need a different size.'));
934
+ console.log(chalk.dim(' url is a PATH (starts with /) — the proxy routes it and intercepts API calls'));
935
+ console.log(chalk.dim(' mockData.routes provides data for API calls the component makes internally'));
936
+ console.log(chalk.dim(' (omit mockData if the component has no internal API calls)'));
937
+ console.log(chalk.yellow(' 5. IMPORTANT: Check the register response for `clientErrors` array'));
938
+ console.log(chalk.yellow(' If clientErrors is non-empty → fix the isolation route and re-register'));
939
+ console.log(chalk.yellow(' Fix client errors and re-register before moving on'));
940
+ console.log(chalk.dim(' Isolation routes are committed to git — the layout guard blocks them in production'));
455
941
  console.log();
456
942
  console.log(chalk.bold('Library Functions — run tests:'));
457
- console.log(chalk.dim(' `codeyam analyze` does NOT test library functions. The tests'));
458
- console.log(chalk.dim(' you wrote in step 4 are the only coverage for these functions.'));
459
- checkbox('Run ALL test files created in step 4');
943
+ checkbox('Run ALL test files created in step 5');
460
944
  console.log(chalk.dim(' Example: npx vitest run app/lib/drinks.test.ts'));
461
945
  checkbox('Verify every test passes');
462
946
  checkbox('If any test fails, fix the source code and re-run');
463
947
  console.log();
464
- console.log(chalk.dim('Do not proceed until both visual analyses and library tests pass.'));
465
- stopGate(6);
948
+ console.log(chalk.dim('Do not proceed until both component isolations and library tests pass.'));
949
+ console.log();
950
+ checkbox('Run `codeyam editor audit` to verify all components have scenarios and all functions have tests');
951
+ console.log();
952
+ console.log(chalk.bold('Build import graph (for change tracking):'));
953
+ checkbox('Run `codeyam editor analyze-imports`');
954
+ console.log(chalk.dim(' This populates the import graph so the system can detect impacted entities when code changes.'));
955
+ console.log(chalk.dim(' It must run AFTER the audit passes so the glossary and entity data are complete.'));
956
+ stopGate(7);
466
957
  }
467
- // ─── Step 7: App Scenarios ────────────────────────────────────────────
468
- function printStep7(root, feature) {
958
+ // ─── Step 8: App Scenarios ────────────────────────────────────────────
959
+ function printStep8(root, feature) {
469
960
  const port = getServerPort();
961
+ const prevState = readState(root);
962
+ const isResuming = prevState?.step === 8;
963
+ const now = new Date().toISOString();
470
964
  writeState(root, {
471
965
  feature,
472
- step: 7,
473
- label: STEP_LABELS[7],
474
- startedAt: new Date().toISOString(),
966
+ step: 8,
967
+ label: STEP_LABELS[8],
968
+ startedAt: isResuming ? prevState.startedAt : now,
969
+ featureStartedAt: prevState?.featureStartedAt || now,
475
970
  });
476
- logEvent(root, 'step', { step: 7, label: 'App Scenarios', feature });
477
- stepHeader(7, 'App Scenarios', feature);
971
+ logEvent(root, 'step', { step: 8, label: 'App Scenarios', feature });
972
+ stepHeader(8, 'App Scenarios', feature);
973
+ if (isResuming) {
974
+ printResumptionHeader(8);
975
+ }
478
976
  console.log('Create app-level scenarios representing different data states.');
479
977
  console.log();
480
978
  console.log(chalk.bold('Checklist:'));
481
- checkbox('Create scenarios for key data states (empty, loaded, error)');
482
- console.log(chalk.dim(' Each scenario provides data across ALL API routes for that state'));
483
- checkbox('Register each scenario (auto-captures screenshot):');
484
- console.log(chalk.dim(` curl -s -X POST http://localhost:${port}/api/editor-register-scenario \\`));
485
- console.log(chalk.dim(` -H 'Content-Type: application/json' \\`));
486
- console.log(chalk.dim(` -d '{"name":"...","description":"...","mockData":{"routes":{"/api/...":{"body":[...]}}}}'`));
487
- checkbox('Create a journal entry for the feature:');
488
- console.log(chalk.dim(` curl -s -X POST http://localhost:${port}/api/editor-journal-entry \\`));
489
- console.log(chalk.dim(` -H 'Content-Type: application/json' \\`));
490
- console.log(chalk.dim(` -d '{"title":"...","type":"feature","description":"...","scenarios":["..."]}'`));
491
- console.log();
492
- console.log(chalk.dim('Do NOT modify application code. Create and register app-level scenarios only.'));
493
- stopGate(7);
979
+ checkbox('Check existing scenarios: `codeyam editor scenarios`');
980
+ console.log(chalk.dim(' Review existing scenarios reuse and update their data rather than'));
981
+ console.log(chalk.dim(' creating duplicates. Re-register with the same name to update a scenario.'));
982
+ checkbox('Ensure scenarios clearly demonstrate what changed in this session');
983
+ console.log(chalk.dim(' If data models changed: update existing scenarios seed data to match'));
984
+ console.log(chalk.dim(' If UI changed: re-register existing scenarios so screenshots reflect the update'));
985
+ console.log(chalk.dim(' Add new scenarios only for genuinely new data states not covered by existing ones'));
986
+ checkbox('Cover key data states for EVERY page/route (at least 2-3 scenarios per page)');
987
+ console.log(chalk.yellow(' Each page needs its own scenarios — a detail page needs different data than the catalog'));
988
+ console.log(chalk.dim(' Catalog: "Full Catalog", "Empty Catalog", "Single Category"'));
989
+ console.log(chalk.dim(' Detail: "Detail - With Reviews", "Detail - No Reviews", "Detail - High Rated"'));
990
+ console.log(chalk.dim(' Each scenario provides seed data to populate the database for that state'));
991
+ checkbox('If the project has a database + seed adapter, use seed-based scenarios:');
992
+ console.log(chalk.dim(` codeyam editor register '{"name":"Full Catalog","type":"application","url":"/","seed":{"products":[...],"categories":[...]}}'`));
993
+ console.log(chalk.dim(' Seed data is written to the DB via the seed adapter. Real app renders real data.'));
994
+ checkbox('Optional: add "viewportWidth" and "viewportHeight" to override the project default screen size');
995
+ console.log(chalk.dim(' If omitted, captures use the project default from setup. Only override for scenarios that need a different size.'));
996
+ checkbox('IMPORTANT: Always include "url" — the page path to screenshot for this scenario');
997
+ console.log(chalk.dim(' Use "/" for home page, "/drinks/1" for detail pages, etc.'));
998
+ console.log(chalk.dim(' Without url, the screenshot captures the root page regardless of the scenario.'));
999
+ console.log(chalk.yellow(' Create separate scenarios for each page that shows different data.'));
1000
+ checkbox('For large seed data, write JSON to a project temp file and use @ prefix:');
1001
+ console.log(chalk.dim(' Write JSON to .codeyam/tmp/scenario.json then register with:'));
1002
+ console.log(chalk.dim(' codeyam editor register @.codeyam/tmp/scenario.json'));
1003
+ checkbox('For external API mocks (Stripe, weather, etc.), add externalApis:');
1004
+ console.log(chalk.dim(` "externalApis":{"GET https://api.stripe.com/v1/prices":{"body":[...],"status":200}}`));
1005
+ checkbox('If the app uses auth, email, or other patterns: see FEATURE_PATTERNS.md for scenario guidance');
1006
+ checkbox('If no database, use component-style mock scenarios (unchanged):');
1007
+ console.log(chalk.dim(` codeyam editor register '{"name":"Empty","description":"...","url":"/","mockData":{"routes":{"/api/...":{"body":[...]}}}}'`));
1008
+ checkbox('After each registration, check the response for `clientErrors`');
1009
+ console.log(chalk.yellow(' If clientErrors is non-empty → fix the issue and re-register the scenario'));
1010
+ console.log(chalk.yellow(' Fix client errors and re-register before moving on'));
1011
+ console.log();
1012
+ console.log(chalk.dim('Focus on creating and registering app-level scenarios. Code fixes happen in step 10 if needed.'));
1013
+ stopGate(8);
494
1014
  }
495
- // ─── Step 8: User Scenarios ───────────────────────────────────────────
496
- function printStep8(root, feature) {
1015
+ // ─── Step 9: User Scenarios ───────────────────────────────────────────
1016
+ function printStep9(root, feature) {
497
1017
  const port = getServerPort();
1018
+ const prevState = readState(root);
1019
+ const isResuming = prevState?.step === 9;
1020
+ const now = new Date().toISOString();
498
1021
  writeState(root, {
499
1022
  feature,
500
- step: 8,
501
- label: STEP_LABELS[8],
502
- startedAt: new Date().toISOString(),
1023
+ step: 9,
1024
+ label: STEP_LABELS[9],
1025
+ startedAt: isResuming ? prevState.startedAt : now,
1026
+ featureStartedAt: prevState?.featureStartedAt || now,
503
1027
  });
504
- logEvent(root, 'step', { step: 8, label: 'User Scenarios', feature });
505
- stepHeader(8, 'User Scenarios', feature);
506
- console.log('Create per-persona scenarios if the app has users. Skip to step 9 if no users.');
1028
+ logEvent(root, 'step', { step: 9, label: 'User Scenarios', feature });
1029
+ stepHeader(9, 'User Scenarios', feature);
1030
+ if (isResuming) {
1031
+ printResumptionHeader(9);
1032
+ }
1033
+ console.log('Create per-persona scenarios if the app has users. Skip to step 10 if no users.');
507
1034
  console.log();
508
1035
  console.log(chalk.bold('If the app has users:'));
509
- checkbox('Create scenarios for each user persona (admin, regular user, new user)');
510
- console.log(chalk.dim(' Each persona scenario provides data across ALL API routes for that user type'));
511
- checkbox('Register each persona scenario (auto-captures screenshot):');
512
- console.log(chalk.dim(` curl -s -X POST http://localhost:${port}/api/editor-register-scenario \\`));
513
- console.log(chalk.dim(` -H 'Content-Type: application/json' \\`));
514
- console.log(chalk.dim(` -d '{"name":"...","description":"...","mockData":{"routes":{"/api/...":{"body":[...]}}}}'`));
1036
+ checkbox('Check existing scenarios: `codeyam editor scenarios`');
1037
+ console.log(chalk.dim(' Reuse existing persona scenarios update data to reflect current changes.'));
1038
+ console.log(chalk.dim(' Re-register with the same name to update. Only add new personas if needed.'));
1039
+ checkbox('Ensure scenarios for each user persona (admin, regular user, new user)');
1040
+ console.log(chalk.dim(' Each persona scenario layers user-specific seed data on top of an app scenario'));
1041
+ checkbox('If using seed-based scenarios, register with type "user" and baseScenario:');
1042
+ console.log(chalk.dim(` codeyam editor register '{"name":"Admin User","type":"user","url":"/","baseScenario":"<app-scenario-id>","seed":{"users":[{"id":1,"role":"admin"}]}}'`));
1043
+ console.log(chalk.dim(' Always include "url" — the page to screenshot (e.g. "/", "/dashboard", "/drinks/1")'));
1044
+ console.log(chalk.dim(" The base scenario's seed data is merged with this scenario's seed data (overlay wins)."));
1045
+ checkbox('If the app uses auth or other patterns: see FEATURE_PATTERNS.md for per-persona scenario guidance');
1046
+ checkbox('If using mock-based scenarios, register with mockData as before:');
1047
+ console.log(chalk.dim(` codeyam editor register '{"name":"...","description":"...","mockData":{"routes":{"/api/...":{"body":[...]}}}}'`));
1048
+ checkbox('After each registration, check the response for `clientErrors`');
1049
+ console.log(chalk.yellow(' If clientErrors is non-empty → fix the issue and re-register the scenario'));
1050
+ console.log(chalk.yellow(' Fix client errors and re-register before moving on'));
515
1051
  console.log();
516
1052
  console.log(chalk.bold('If the app has NO users:'));
517
- console.log(chalk.dim(' Skip this step and proceed to step 9 (Verify).'));
1053
+ console.log(chalk.dim(' Skip this step and proceed to step 10 (Verify).'));
518
1054
  console.log();
519
- console.log(chalk.dim('Do NOT modify application code. Create user-persona scenarios only (or skip if no users).'));
520
- stopGate(8);
1055
+ console.log(chalk.dim('Focus on creating user-persona scenarios (or skip if no users). Code fixes happen in step 10 if needed.'));
1056
+ stopGate(9);
521
1057
  }
522
- // ─── Step 9: Verify ──────────────────────────────────────────────────
523
- function printStep9(root, feature) {
1058
+ // ─── Step 10: Verify ──────────────────────────────────────────────────
1059
+ function printStep10(root, feature) {
524
1060
  const port = getServerPort();
1061
+ const prevState = readState(root);
1062
+ const isResuming = prevState?.step === 10;
1063
+ const now = new Date().toISOString();
525
1064
  writeState(root, {
526
1065
  feature,
527
- step: 9,
528
- label: STEP_LABELS[9],
529
- startedAt: new Date().toISOString(),
1066
+ step: 10,
1067
+ label: STEP_LABELS[10],
1068
+ startedAt: isResuming ? prevState.startedAt : now,
1069
+ featureStartedAt: prevState?.featureStartedAt || now,
530
1070
  });
531
- logEvent(root, 'step', { step: 9, label: 'Verify', feature });
532
- stepHeader(9, 'Verify', feature);
533
- console.log('Verify entity screenshots, editor scenarios, and library tests. After ANY code fix, re-analyze affected files.');
534
- console.log();
535
- console.log(chalk.bold('Entity screenshots (Data tab) — verify via API:'));
536
- checkbox(`Check entity status: \`curl -s http://localhost:${port}/api/editor-entity-status\``);
537
- checkbox('Review `summary.missingScreenshots` — each listed entity needs `codeyam analyze --noOpen <file>`');
538
- checkbox('Open the Data tab and review each entity screenshot for visual correctness');
1071
+ logEvent(root, 'step', { step: 10, label: 'Verify', feature });
1072
+ stepHeader(10, 'Verify', feature);
1073
+ if (isResuming) {
1074
+ printResumptionHeader(10);
1075
+ }
1076
+ console.log('Verify component isolation screenshots, editor scenarios, and library tests.');
1077
+ console.log();
1078
+ console.log(chalk.bold('Component isolation screenshots verify:'));
1079
+ checkbox('Review component screenshots in the App tab (grouped under Components)');
539
1080
  checkbox('If any screenshot looks wrong, fix the component code');
540
- console.log(chalk.yellow(' IMPORTANT: After fixing ANY visual component, re-run `codeyam analyze --noOpen <file>`'));
541
- console.log(chalk.yellow(' to update the entity screenshot. Re-capturing an editor scenario is NOT sufficient.'));
1081
+ console.log(chalk.yellow(' After fixing a visual component, re-register the affected scenarios:'));
1082
+ console.log(chalk.dim(` codeyam editor register '{"name":"ComponentName - Scenario",...}'`));
542
1083
  console.log();
543
1084
  console.log(chalk.bold('Editor scenarios (App tab) — visual + error check:'));
544
- checkbox(`Refresh the preview: \`curl -s -X POST http://localhost:${port}/api/editor-refresh\``);
1085
+ checkbox(`Refresh the preview: \`codeyam editor preview\``);
545
1086
  checkbox('Click through each app-level and user-persona scenario in the preview');
546
- checkbox('Check for visual correctness and client-side errors (Console tab)');
547
- console.log(chalk.dim(' Look for: React errors, failed fetches, undefined references, hydration mismatches'));
548
- checkbox('If any errors found, fix the source code and re-test');
549
- console.log(chalk.yellow(' After fixing code that affects visual components, also re-run `codeyam analyze --noOpen <file>`'));
1087
+ checkbox('For seed-based scenarios: verify data renders correctly after switching');
1088
+ console.log(chalk.dim(' Switch between scenarios and confirm the app reflects the seeded data each time'));
1089
+ checkbox(`Check for client-side errors: \`codeyam editor client-errors\``);
1090
+ console.log(chalk.yellow(' If `hasErrors` is true: list each scenario with errors, fix the source code,'));
1091
+ console.log(chalk.yellow(' re-register the affected scenarios, and re-check until hasErrors is false'));
1092
+ console.log(chalk.dim(' Common errors: React errors, failed fetches, undefined references, hydration mismatches'));
1093
+ checkbox('Verify no broken images: `codeyam editor verify-images \'{"paths":["/"], "imageUrls":["url1"]}\'` with all page paths and image URLs');
550
1094
  console.log();
551
1095
  console.log(chalk.bold('Library functions — test check:'));
552
- checkbox('Re-run all test files from step 4 to confirm they still pass');
1096
+ checkbox('Re-run all test files from step 5 to confirm they still pass');
553
1097
  console.log(chalk.dim(' Example: npx vitest run app/lib/drinks.test.ts'));
554
1098
  checkbox('If any test fails, fix the source code and re-run');
555
1099
  console.log();
556
- console.log(chalk.dim('Do NOT add new features. Fix issues only. All entity screenshots, scenarios, and tests must be clean.'));
557
- stopGate(9);
1100
+ console.log(chalk.dim('Focus on fixing issues. All component screenshots, scenarios, and tests must be clean before proceeding.'));
1101
+ stopGate(10);
558
1102
  }
559
- // ─── Step 10: Review ──────────────────────────────────────────────────
560
- function printStep10(root, feature) {
1103
+ // ─── Step 11: Journal ─────────────────────────────────────────────────
1104
+ function printStep11(root, feature) {
561
1105
  const port = getServerPort();
1106
+ const prevState = readState(root);
1107
+ const isResuming = prevState?.step === 11;
1108
+ const now = new Date().toISOString();
562
1109
  writeState(root, {
563
1110
  feature,
564
- step: 10,
565
- label: STEP_LABELS[10],
566
- startedAt: new Date().toISOString(),
1111
+ step: 11,
1112
+ label: STEP_LABELS[11],
1113
+ startedAt: isResuming ? prevState.startedAt : now,
1114
+ featureStartedAt: prevState?.featureStartedAt || now,
567
1115
  });
568
- logEvent(root, 'step', { step: 10, label: 'Review', feature });
569
- stepHeader(10, 'Review', feature);
570
- console.log('Present a full summary, verify screenshots, then let the user save or revise.');
571
- console.log();
572
- console.log(chalk.bold('Phase 1 — Summary:'));
573
- checkbox('Summarize the feature that was built');
574
- checkbox('List all components and functions created');
575
- checkbox('List glossary entries added in step 5');
576
- checkbox('List all scenarios (app-level and user-persona)');
577
- checkbox('Report analysis status (completed/in-progress from step 6)');
578
- checkbox('Report verification status from step 9 (all clean?)');
579
- checkbox(`Refresh the preview: \`curl -s -X POST http://localhost:${port}/api/dev-mode-refresh\``);
580
- console.log();
581
- console.log(chalk.bold('Phase 2 Screenshot & error verification:'));
582
- console.log(chalk.yellow(' CRITICAL: Verify screenshots AND check for client-side errors.'));
583
- console.log();
584
- console.log(chalk.bold(' Entity screenshots:'));
585
- checkbox(`Check entity status: \`curl -s http://localhost:${port}/api/editor-entity-status\``);
586
- checkbox('Review `summary.missingScreenshots` — each listed entity needs `codeyam analyze --noOpen <file>`');
587
- checkbox('For each component created in this feature, confirm it has a screenshot in the Data tab');
588
- console.log();
589
- console.log(chalk.bold(' Client-side errors:'));
590
- checkbox(`Check for errors: \`curl -s http://localhost:${port}/api/editor-client-errors\``);
591
- checkbox('If `hasErrors` is true, list the errors and fix them in the source code');
592
- checkbox('After fixing, re-capture affected scenarios to clear the errors');
593
- console.log();
594
- checkbox('Do NOT proceed until all components have screenshots AND client errors are resolved');
595
- console.log();
596
- checkbox('Present the summary (with screenshot and error status) to the user');
597
- console.log();
598
- console.log(chalk.bold('Phase 3 Present a selection menu to the user (use AskUserQuestion):'));
599
- console.log(chalk.green(' "Save & commit"') +
1116
+ logEvent(root, 'step', { step: 11, label: 'Journal', feature });
1117
+ stepHeader(11, 'Journal', feature);
1118
+ if (isResuming) {
1119
+ printResumptionHeader(11);
1120
+ }
1121
+ console.log('Create or update the journal entry for this feature.');
1122
+ console.log();
1123
+ console.log(chalk.bold('Checklist:'));
1124
+ checkbox('Write a concise description of what was built (2-3 sentences)');
1125
+ checkbox(`First time at step 11 create journal entry with ALL session screenshots:`);
1126
+ console.log(chalk.dim(` codeyam editor journal '{"title":"...","type":"feature","description":"...","includeSessionScenarios":true}'`));
1127
+ console.log(chalk.dim(' includeSessionScenarios auto-discovers component + app + user persona screenshots'));
1128
+ checkbox(`Returning to step 11 (before commit) — update the existing journal entry:`);
1129
+ console.log(chalk.dim(` codeyam editor journal-update '{"time":"<journal entry time>","description":"<updated>","includeSessionScenarios":true}'`));
1130
+ console.log(chalk.dim(' Note: PATCH only works before the entry is committed. After commit, use POST to create a new entry.'));
1131
+ console.log();
1132
+ console.log(chalk.dim('Focus on creating or updating the journal entry. Summary and presentation happen in step 13.'));
1133
+ stopGate(11);
1134
+ }
1135
+ // ─── Step 12: Review ──────────────────────────────────────────────────
1136
+ function printStep12(root, feature) {
1137
+ const port = getServerPort();
1138
+ const prevState = readState(root);
1139
+ const isResuming = prevState?.step === 12;
1140
+ const now = new Date().toISOString();
1141
+ writeState(root, {
1142
+ feature,
1143
+ step: 12,
1144
+ label: STEP_LABELS[12],
1145
+ startedAt: isResuming ? prevState.startedAt : now,
1146
+ featureStartedAt: prevState?.featureStartedAt || now,
1147
+ });
1148
+ logEvent(root, 'step', { step: 12, label: 'Review', feature });
1149
+ stepHeader(12, 'Review', feature);
1150
+ if (isResuming) {
1151
+ printResumptionHeader(12);
1152
+ }
1153
+ console.log('Verify all screenshots and checks pass before presenting to the user.');
1154
+ console.log();
1155
+ console.log(chalk.bold('Checklist (do all of this silently):'));
1156
+ checkbox(`Refresh the preview: \`codeyam editor preview\``);
1157
+ checkbox('Verify each component has screenshots in the App tab (grouped under Components)');
1158
+ checkbox('If any are missing, re-register them using `codeyam editor register`');
1159
+ checkbox(`Check for client errors: \`codeyam editor client-errors\``);
1160
+ checkbox('If `hasErrors` is true, fix them and re-capture affected scenarios');
1161
+ checkbox('Run `codeyam editor verify-images \'{"paths":["/"], "imageUrls":["url1"]}\'` with all page paths and image URLs');
1162
+ checkbox('Fix or remove any broken images before continuing');
1163
+ checkbox('Run `codeyam editor audit` to verify completeness of scenarios and tests');
1164
+ checkbox('Do not proceed until all checks pass');
1165
+ stopGate(12);
1166
+ }
1167
+ // ─── Step 13: Present ─────────────────────────────────────────────────
1168
+ function printStep13(root, feature) {
1169
+ const port = getServerPort();
1170
+ const prevState = readState(root);
1171
+ const isResuming = prevState?.step === 13;
1172
+ const now = new Date().toISOString();
1173
+ writeState(root, {
1174
+ feature,
1175
+ step: 13,
1176
+ label: STEP_LABELS[13],
1177
+ startedAt: isResuming ? prevState.startedAt : now,
1178
+ featureStartedAt: prevState?.featureStartedAt || now,
1179
+ });
1180
+ logEvent(root, 'step', { step: 13, label: 'Present', feature });
1181
+ stepHeader(13, 'Present', feature);
1182
+ if (isResuming) {
1183
+ printResumptionHeader(13);
1184
+ }
1185
+ console.log('Present the results to the user and get their approval.');
1186
+ console.log();
1187
+ console.log(chalk.bold('Checklist:'));
1188
+ checkbox('Fetch all scenarios: `codeyam editor scenarios`');
1189
+ console.log(chalk.dim(' Each scenario has a `changeStatus` field: "new", "edited", "impacted", or null.'));
1190
+ checkbox('Pick the best scenario to showcase from this working session:');
1191
+ console.log(chalk.dim(' Prefer scenarios with changeStatus "new" or "edited" (directly changed in this session).'));
1192
+ console.log(chalk.dim(' For app-level scenarios, prefer those showing the new/changed functionality.'));
1193
+ console.log(chalk.dim(' NEVER pick a scenario with changeStatus null — those are unchanged from a previous commit.'));
1194
+ checkbox('Switch the preview to that scenario using its `id`:');
1195
+ console.log(chalk.dim(` codeyam editor preview '{"scenarioId":"<id>"}'`));
1196
+ checkbox(`Show the results panel: \`codeyam editor show-results\``);
1197
+ console.log(chalk.dim(' This opens a visual panel below the terminal showing all scenarios with screenshots.'));
1198
+ console.log(chalk.dim(' The user can click scenarios to switch the live preview.'));
1199
+ checkbox('Write a 1-2 sentence summary of what was built');
1200
+ checkbox('Report test count and audit status (one line)');
1201
+ console.log();
1202
+ console.log(chalk.bold('Present a selection menu to the user (use AskUserQuestion with these EXACT option labels):'));
1203
+ console.log(chalk.green(' Option 1 label: "Save & commit"') +
600
1204
  chalk.dim(' — git commit all changes and record in journal'));
601
- console.log(chalk.yellow(' "I\'d like to make some changes"') +
1205
+ console.log(chalk.yellow(' Option 2 label: "I\'d like to make some changes"') +
602
1206
  chalk.dim(' — describe changes, then re-verify'));
603
1207
  console.log();
604
1208
  console.log(chalk.bold('If the user chooses "Save & commit":'));
605
- checkbox(`Git commit all changes: \`curl -s -X POST http://localhost:${port}/api/editor-commit -H 'Content-Type: application/json' -d '{"message":"feat: <feature name>"}'\``);
606
- checkbox(`Update journal entry with commit SHA: \`curl -s -X PATCH http://localhost:${port}/api/editor-journal-update -H 'Content-Type: application/json' -d '{"time":"<journal entry time>","commitSha":"<sha>","commitMessage":"feat: <feature name>"}'\``);
1209
+ checkbox(`Hide the results panel first: \`codeyam editor hide-results\``);
1210
+ checkbox(`Git commit using the journal description: \`codeyam editor commit '{"message":"feat: <title>\\n\\n<journal description>"}'\``);
1211
+ console.log(chalk.dim(' The commit message body MUST match the journal description exactly'));
1212
+ checkbox(`Update journal with commit SHA: \`codeyam editor journal-update '{"time":"<journal entry time>","commitSha":"<sha>","commitMessage":"feat: <title>"}'\``);
607
1213
  console.log(chalk.green(' Then run: ') +
608
- chalk.bold('codeyam editor 1') +
1214
+ chalk.bold('codeyam editor steps') +
609
1215
  chalk.green(' to start the next feature'));
610
1216
  console.log();
611
- console.log(chalk.bold('If the user chooses "Make changes":'));
612
- checkbox('Ask what changes the user wants');
613
- checkbox('Make the requested changes');
614
- checkbox(`Update the journal entry description: \`curl -s -X PATCH http://localhost:${port}/api/editor-journal-update -H 'Content-Type: application/json' -d '{"time":"<journal entry time>","description":"<updated description>"}'\``);
615
- console.log(chalk.yellow(' Then run: ') +
616
- chalk.bold('codeyam editor 9') +
617
- chalk.yellow(' to re-verify, which flows back to step 10'));
1217
+ console.log(chalk.red.bold(' If the user reports a bug or requests a fix after committing:'));
1218
+ console.log(chalk.red.bold(' You MUST still run `codeyam editor change` before making any changes.'));
1219
+ console.log(chalk.red.bold(' The change workflow applies to ALL changes — post-commit fixes are not an exception.'));
1220
+ console.log();
1221
+ console.log(chalk.bold('If the user chooses "Make changes" (or asks for ANY change, even as a question):'));
1222
+ checkbox(`Hide the results panel: \`codeyam editor hide-results\``);
1223
+ checkbox('Ask what changes the user wants (if not already clear)');
1224
+ checkbox(`Run: \`codeyam editor change "${feature}"\` — this gives you the change checklist`);
1225
+ checkbox('THEN make the requested changes and follow the checklist');
1226
+ console.log(chalk.red.bold(' IMPORTANT: Always run the change command BEFORE writing any code.'));
1227
+ stopGate(13, { confirm: true });
1228
+ }
1229
+ // ─── Command definition ───────────────────────────────────────────────
1230
+ // ─── Analyze-imports subcommand ────────────────────────────────────────
1231
+ /**
1232
+ * `codeyam editor analyze-imports`
1233
+ *
1234
+ * Runs data-structure-only analysis for all glossary entities, then outputs
1235
+ * an import graph and entity data structures as JSON to stdout.
1236
+ */
1237
+ async function handleAnalyzeImports() {
1238
+ const root = getProjectRoot();
1239
+ // Read glossary
1240
+ const glossaryPath = path.join(root, '.codeyam', 'glossary.json');
1241
+ if (!fs.existsSync(glossaryPath)) {
1242
+ console.error(chalk.red('Error: .codeyam/glossary.json not found.'));
1243
+ console.error(chalk.dim(' Run codeyam editor 6 to create the glossary first.'));
1244
+ process.exit(1);
1245
+ }
1246
+ let glossaryEntries;
1247
+ try {
1248
+ glossaryEntries = JSON.parse(fs.readFileSync(glossaryPath, 'utf8'));
1249
+ }
1250
+ catch {
1251
+ console.error(chalk.red('Error: Could not parse .codeyam/glossary.json.'));
1252
+ process.exit(1);
1253
+ }
1254
+ if (!Array.isArray(glossaryEntries) || glossaryEntries.length === 0) {
1255
+ console.error(chalk.red('Error: glossary.json is empty.'));
1256
+ process.exit(1);
1257
+ }
1258
+ const filePaths = glossaryEntries.map((e) => e.filePath);
1259
+ const entityNames = glossaryEntries.map((e) => e.name);
1260
+ const progress = new ProgressReporter();
1261
+ // Run data-structure-only analysis for all entities
1262
+ progress.start('Running import analysis for all glossary entities...');
1263
+ try {
1264
+ await runAnalysisForEntities({
1265
+ projectRoot: root,
1266
+ filePaths,
1267
+ entityNames,
1268
+ progress,
1269
+ onlyDataStructure: true,
1270
+ });
1271
+ }
1272
+ catch (err) {
1273
+ progress.fail('Analysis failed');
1274
+ const msg = err instanceof Error ? err.message : String(err);
1275
+ console.error(chalk.red(`Error: ${msg}`));
1276
+ process.exit(1);
1277
+ }
1278
+ progress.succeed('Analysis complete');
1279
+ // Load entities WITH metadata from database
1280
+ progress.start('Loading entity metadata...');
1281
+ await initializeEnvironment();
1282
+ const entities = await loadEntities({});
1283
+ if (!entities || entities.length === 0) {
1284
+ progress.succeed('No entities found in database yet — skipping import analysis. This is normal on the first feature.');
1285
+ console.log(JSON.stringify({ imports: {}, entities: {} }));
1286
+ return;
1287
+ }
1288
+ // Deduplicate to latest versions
1289
+ const latestByKey = new Map();
1290
+ for (const entity of entities) {
1291
+ const key = `${entity.name}::${entity.filePath}`;
1292
+ const existing = latestByKey.get(key);
1293
+ if (!existing ||
1294
+ (entity.createdAt &&
1295
+ existing.createdAt &&
1296
+ entity.createdAt > existing.createdAt)) {
1297
+ latestByKey.set(key, entity);
1298
+ }
1299
+ }
1300
+ const entityNameSet = new Set(entityNames);
1301
+ const latestEntities = [...latestByKey.values()].filter((e) => entityNameSet.has(e.name));
1302
+ // Build import graph from importedExports metadata
1303
+ const imports = {};
1304
+ const entityData = {};
1305
+ // Also load analyses for data structures
1306
+ const entityShas = latestEntities.map((e) => e.sha);
1307
+ const analyses = await loadAnalyses({ entityShas });
1308
+ const analysisMap = new Map();
1309
+ if (analyses) {
1310
+ for (const a of analyses) {
1311
+ if (!analysisMap.has(a.entitySha) ||
1312
+ (a.createdAt &&
1313
+ (!analysisMap.get(a.entitySha).createdAt ||
1314
+ a.createdAt > analysisMap.get(a.entitySha).createdAt))) {
1315
+ analysisMap.set(a.entitySha, a);
1316
+ }
1317
+ }
1318
+ }
1319
+ for (const entity of latestEntities) {
1320
+ const importedExports = entity.metadata?.importedExports || [];
1321
+ const importedNames = importedExports
1322
+ .map((ie) => ie.name)
1323
+ .filter((name) => entityNameSet.has(name));
1324
+ if (importedNames.length > 0) {
1325
+ imports[entity.name] = importedNames;
1326
+ }
1327
+ // Collect entity data with analysis data structures
1328
+ const analysis = analysisMap.get(entity.sha);
1329
+ const analysisMetadata = analysis?.metadata;
1330
+ entityData[entity.name] = {
1331
+ filePath: entity.filePath || '',
1332
+ entityType: entity.entityType || 'visual',
1333
+ dataForMocks: analysisMetadata?.scenariosDataStructure?.dataForMocks,
1334
+ dependencySchemas: analysisMetadata?.mergedDataStructure?.dependencySchemas,
1335
+ };
1336
+ }
1337
+ progress.succeed('Done');
1338
+ // Output combined JSON
1339
+ const output = { imports, entities: entityData };
1340
+ console.log(JSON.stringify(output, null, 2));
1341
+ }
1342
+ // ─── Validate-seed subcommand ─────────────────────────────────────────
1343
+ /**
1344
+ * Validate seed data structure and check for a seed adapter.
1345
+ * Usage: codeyam editor validate-seed '{"products":[...]}'
1346
+ */
1347
+ function handleValidateSeed(jsonArg) {
1348
+ const root = process.cwd();
1349
+ // Check for seed adapter
1350
+ const adapterPath = detectSeedAdapter(root);
1351
+ if (adapterPath) {
1352
+ console.log(chalk.green(`Seed adapter found: ${adapterPath}`));
1353
+ }
1354
+ else {
1355
+ console.log(chalk.yellow('No seed adapter found. Create .codeyam/seed-adapter.ts to use seed-based scenarios.'));
1356
+ }
1357
+ if (!jsonArg) {
1358
+ return;
1359
+ }
1360
+ let data;
1361
+ try {
1362
+ data = JSON.parse(jsonArg);
1363
+ }
1364
+ catch {
1365
+ console.error(chalk.red('Error: Invalid JSON.'));
1366
+ process.exit(1);
1367
+ }
1368
+ const result = validateSeedData(data);
1369
+ if (result.valid) {
1370
+ const tables = Object.keys(data);
1371
+ const totalRows = tables.reduce((sum, t) => sum + (Array.isArray(data[t]) ? data[t].length : 0), 0);
1372
+ console.log(chalk.green(`Seed data valid: ${tables.length} table(s), ${totalRows} total row(s)`));
1373
+ for (const table of tables) {
1374
+ const rows = Array.isArray(data[table])
1375
+ ? data[table].length
1376
+ : 0;
1377
+ console.log(chalk.dim(` ${table}: ${rows} row(s)`));
1378
+ }
1379
+ }
1380
+ else {
1381
+ console.error(chalk.red('Seed data validation failed:'));
1382
+ for (const err of result.errors) {
1383
+ console.error(chalk.red(` - ${err}`));
1384
+ }
1385
+ process.exit(1);
1386
+ }
1387
+ }
1388
+ // ─── Isolate subcommand ───────────────────────────────────────────────
1389
+ /**
1390
+ * `codeyam editor isolate StarRating CategoryBadge DrinkCard`
1391
+ *
1392
+ * Creates isolation route directories and the layout guard file.
1393
+ * This avoids brace-expansion permission prompts in the embedded terminal.
1394
+ */
1395
+ function handleIsolate(componentNames) {
1396
+ const root = process.cwd();
1397
+ if (componentNames.length === 0) {
1398
+ console.error(chalk.red('Usage: codeyam editor isolate ComponentA ComponentB ...'));
1399
+ process.exit(1);
1400
+ }
1401
+ const isolateDir = path.join(root, 'app', 'isolated-components');
1402
+ // Create layout.tsx with production guard if missing
1403
+ const layoutPath = path.join(isolateDir, 'layout.tsx');
1404
+ if (!fs.existsSync(layoutPath)) {
1405
+ fs.mkdirSync(isolateDir, { recursive: true });
1406
+ fs.writeFileSync(layoutPath, [
1407
+ 'import { notFound } from "next/navigation";',
1408
+ '',
1409
+ 'export default function CaptureLayout({ children }: { children: React.ReactNode }) {',
1410
+ ' if (process.env.NODE_ENV === "production") notFound();',
1411
+ ' return <>{children}</>;',
1412
+ '}',
1413
+ '',
1414
+ ].join('\n'), 'utf8');
1415
+ console.log(chalk.green(`Created layout guard: app/isolated-components/layout.tsx`));
1416
+ }
1417
+ // Create a directory for each component
1418
+ const created = [];
1419
+ const existed = [];
1420
+ for (const name of componentNames) {
1421
+ const dir = path.join(isolateDir, name);
1422
+ if (fs.existsSync(dir)) {
1423
+ existed.push(name);
1424
+ }
1425
+ else {
1426
+ fs.mkdirSync(dir, { recursive: true });
1427
+ created.push(name);
1428
+ }
1429
+ }
1430
+ if (created.length > 0) {
1431
+ console.log(chalk.green(`Created ${created.length} isolation route dir(s): ${created.join(', ')}`));
1432
+ }
1433
+ if (existed.length > 0) {
1434
+ console.log(chalk.dim(`Already existed: ${existed.join(', ')}`));
1435
+ }
1436
+ }
1437
+ // ─── Register subcommand ──────────────────────────────────────────────
1438
+ /**
1439
+ * Format API subcommand results as concise one-line summaries.
1440
+ * Prevents Claude from piping output to python3 just to extract key fields.
1441
+ * Returns null for subcommands that should keep raw JSON output.
1442
+ */
1443
+ function formatApiSubcommandResult(subcommand, data) {
1444
+ if (!data || typeof data !== 'object')
1445
+ return null;
1446
+ switch (subcommand) {
1447
+ case 'journal': {
1448
+ const parts = [`success=${data.success}`];
1449
+ if (data.entry?.time)
1450
+ parts.push(`time="${data.entry.time}"`);
1451
+ if (data.entry?.title)
1452
+ parts.push(`title="${data.entry.title}"`);
1453
+ if (data.scenarioScreenshotsFound != null) {
1454
+ parts.push(`screenshots=${data.scenarioScreenshotsFound}`);
1455
+ }
1456
+ return parts.join(' ');
1457
+ }
1458
+ case 'journal-update': {
1459
+ const parts = [`success=${data.success}`];
1460
+ if (data.entry?.time)
1461
+ parts.push(`time="${data.entry.time}"`);
1462
+ if (data.scenarioScreenshotsFound != null) {
1463
+ parts.push(`screenshots=${data.scenarioScreenshotsFound}`);
1464
+ }
1465
+ return parts.join(' ');
1466
+ }
1467
+ case 'commit': {
1468
+ const parts = [`success=${data.success}`];
1469
+ if (data.sha)
1470
+ parts.push(`sha=${data.sha}`);
1471
+ if (data.message)
1472
+ parts.push(`message="${data.message.split('\n')[0]}"`);
1473
+ return parts.join(' ');
1474
+ }
1475
+ case 'preview': {
1476
+ const parts = [
1477
+ `success=${!!data.ok || data.success !== false}`,
1478
+ ];
1479
+ if (data.path)
1480
+ parts.push(`path="${data.path}"`);
1481
+ if (data.scenarioId)
1482
+ parts.push(`scenarioId="${data.scenarioId}"`);
1483
+ if (data.sessionsNotified != null)
1484
+ parts.push(`notified=${data.sessionsNotified}`);
1485
+ return parts.join(' ');
1486
+ }
1487
+ case 'dev-server': {
1488
+ if (data.status) {
1489
+ const parts = [`status=${data.status}`, `pid=${data.pid || 'none'}`];
1490
+ if (data.url)
1491
+ parts.push(`url=${data.url}`);
1492
+ if (data.proxyUrl)
1493
+ parts.push(`proxyUrl=${data.proxyUrl}`);
1494
+ if (data.errorMessage)
1495
+ parts.push(`error: ${data.errorMessage}`);
1496
+ return parts.join(' ');
1497
+ }
1498
+ return null;
1499
+ }
1500
+ case 'client-errors': {
1501
+ const parts = [`hasErrors=${data.hasErrors}`];
1502
+ parts.push(`totalErrors=${data.totalErrors ?? 0}`);
1503
+ if (data.livePreview) {
1504
+ const lp = data.livePreview;
1505
+ parts.push(`livePreview=${lp.loaded ? 'loaded' : 'not-loaded'}`);
1506
+ if (lp.loaded) {
1507
+ parts.push(`hasContent=${lp.hasContent}`);
1508
+ }
1509
+ const liveErrors = lp.errors?.length ?? 0;
1510
+ parts.push(`liveErrors=${liveErrors}`);
1511
+ if (liveErrors > 0) {
1512
+ // Show first few error messages for context
1513
+ for (const err of lp.errors.slice(0, 3)) {
1514
+ parts.push(` error: ${err.message}`);
1515
+ }
1516
+ }
1517
+ }
1518
+ else {
1519
+ parts.push('livePreview=not-loaded');
1520
+ }
1521
+ return parts.join(' ');
1522
+ }
1523
+ default:
1524
+ return null; // journal-list, show/hide-results: keep full JSON
1525
+ }
1526
+ }
1527
+ /**
1528
+ * `codeyam editor register '{"name":"...","componentName":"...",...}'`
1529
+ *
1530
+ * Thin CLI wrapper around POST /api/editor-register-scenario.
1531
+ * Auto-approved via `Bash(codeyam:*)` — no manual approval needed.
1532
+ */
1533
+ async function handleRegister(jsonArg) {
1534
+ if (!jsonArg) {
1535
+ console.error(chalk.red('Error: JSON argument required.'));
1536
+ console.error(chalk.dim(' Usage: codeyam editor register \'{"name":"DrinkCard - Default","componentName":"DrinkCard","url":"/isolated-components/DrinkCard?s=Default"}\''));
1537
+ console.error(chalk.dim(' For large payloads: codeyam editor register @/tmp/scenario.json'));
1538
+ process.exit(1);
1539
+ }
1540
+ const parsed = parseRegisterArg(jsonArg);
1541
+ if (parsed.error) {
1542
+ console.error(chalk.red(`Error: ${parsed.error}`));
1543
+ if (parsed.error === 'Invalid JSON') {
1544
+ console.error(chalk.dim(` Received: ${jsonArg.slice(0, 200)}`));
1545
+ }
1546
+ process.exit(1);
1547
+ }
1548
+ const body = parsed.body;
1549
+ const port = getServerPort();
1550
+ const url = `http://localhost:${port}/api/editor-register-scenario`;
1551
+ try {
1552
+ const res = await fetch(url, {
1553
+ method: 'POST',
1554
+ headers: { 'Content-Type': 'application/json' },
1555
+ body: JSON.stringify(body),
1556
+ });
1557
+ const data = await res.json();
1558
+ // Print concise summary instead of raw JSON so Claude doesn't need python3
1559
+ const parts = [];
1560
+ parts.push(`success=${data.success}`);
1561
+ if (data.scenario?.name)
1562
+ parts.push(`name="${data.scenario.name}"`);
1563
+ parts.push(`screenshot=${!!data.screenshotCaptured}`);
1564
+ if (data.clientErrors?.length > 0) {
1565
+ parts.push(chalk.red(`errors=${data.clientErrors.length}`));
1566
+ }
1567
+ else {
1568
+ parts.push(`errors=0`);
1569
+ }
1570
+ if (data.seedResult)
1571
+ parts.push(`seed=${data.seedResult.success}`);
1572
+ if (data.captureError)
1573
+ parts.push(chalk.yellow(`captureError="${data.captureError}"`));
1574
+ console.log(parts.join(' '));
1575
+ // Surface client errors prominently so they can't be missed
1576
+ if (data.clientErrors && data.clientErrors.length > 0) {
1577
+ console.log(chalk.red.bold(`⚠ WARNING: ${data.clientErrors.length} client error${data.clientErrors.length !== 1 ? 's' : ''} detected during capture:`));
1578
+ for (const err of data.clientErrors) {
1579
+ console.log(chalk.red(` → ${err}`));
1580
+ }
1581
+ console.log(chalk.yellow(' The screenshot may show an error screen instead of the actual component.'));
1582
+ console.log(chalk.yellow(' Fix the issue and re-register this scenario.'));
1583
+ }
1584
+ if (!res.ok) {
1585
+ console.error(chalk.dim(JSON.stringify(data, null, 2)));
1586
+ process.exit(1);
1587
+ }
1588
+ }
1589
+ catch (error) {
1590
+ const msg = error instanceof Error ? error.message : String(error);
1591
+ console.error(chalk.red(`Error: Could not reach editor server at ${url}`));
1592
+ console.error(chalk.dim(` ${msg}`));
1593
+ console.error(chalk.dim(' Is the editor running? Start it with: codeyam editor'));
1594
+ process.exit(1);
1595
+ }
1596
+ }
1597
+ // ─── Dependents subcommand ────────────────────────────────────────────
1598
+ /**
1599
+ * `codeyam editor dependents <EntityName>`
1600
+ *
1601
+ * Walks the importedBy reverse dependency tree to find all ancestors of a
1602
+ * given entity — i.e., every component or page that transitively imports it.
1603
+ * Used after code changes to determine what needs recapturing.
1604
+ */
1605
+ async function handleDependents(entityName) {
1606
+ if (!entityName) {
1607
+ console.error(chalk.red('Error: Entity name required.'));
1608
+ console.error(chalk.dim(' Usage: codeyam editor dependents DrinkCard'));
1609
+ process.exit(1);
1610
+ }
1611
+ const progress = new ProgressReporter();
1612
+ progress.start('Loading entities from database...');
1613
+ await initializeEnvironment();
1614
+ const allEntities = await loadEntities({});
1615
+ if (!allEntities || allEntities.length === 0) {
1616
+ progress.fail('No entities found in database');
1617
+ console.error(chalk.dim(' Run codeyam editor analyze-imports first to populate entity data.'));
1618
+ process.exit(1);
1619
+ }
1620
+ // Find the target entity by name (case-insensitive match)
1621
+ const targetEntities = allEntities.filter((e) => e.name.toLowerCase() === entityName.toLowerCase());
1622
+ if (targetEntities.length === 0) {
1623
+ progress.fail(`Entity "${entityName}" not found in database`);
1624
+ const names = [...new Set(allEntities.map((e) => e.name))].sort();
1625
+ console.error(chalk.dim(` Available entities: ${names.join(', ')}`));
1626
+ process.exit(1);
1627
+ }
1628
+ progress.succeed('Entities loaded');
1629
+ // Build lookup: entityName -> Set<entityName> of entities that import it.
1630
+ // Each entity's metadata.importedBy is the pre-computed reverse graph:
1631
+ // { [filePath]: { [importerName]: { shas: string[] } } }
1632
+ const importedByName = new Map();
1633
+ for (const entity of allEntities) {
1634
+ const importedBy = entity.metadata?.importedBy;
1635
+ if (!importedBy || typeof importedBy !== 'object')
1636
+ continue;
1637
+ const importers = new Set();
1638
+ for (const filePath of Object.keys(importedBy)) {
1639
+ for (const importerName of Object.keys(importedBy[filePath])) {
1640
+ importers.add(importerName);
1641
+ }
1642
+ }
1643
+ if (importers.size > 0) {
1644
+ importedByName.set(entity.name, importers);
1645
+ }
1646
+ }
1647
+ // BFS walk up the dependency tree from the changed entity
1648
+ const visited = new Set();
1649
+ const result = [];
1650
+ const queue = [
1651
+ { name: entityName, depth: 0 },
1652
+ ];
1653
+ visited.add(entityName.toLowerCase());
1654
+ // Collect entity types for display
1655
+ const entityTypes = new Map();
1656
+ for (const e of allEntities) {
1657
+ if (!entityTypes.has(e.name)) {
1658
+ entityTypes.set(e.name, e.entityType || 'unknown');
1659
+ }
1660
+ }
1661
+ while (queue.length > 0) {
1662
+ const { name, depth } = queue.shift();
1663
+ result.push({
1664
+ name,
1665
+ entityType: entityTypes.get(name) || 'unknown',
1666
+ depth,
1667
+ });
1668
+ // Find all entities that import this one
1669
+ const importers = importedByName.get(name);
1670
+ if (!importers)
1671
+ continue;
1672
+ for (const importerName of importers) {
1673
+ if (visited.has(importerName.toLowerCase()))
1674
+ continue;
1675
+ visited.add(importerName.toLowerCase());
1676
+ queue.push({ name: importerName, depth: depth + 1 });
1677
+ }
1678
+ }
1679
+ // Output
1680
+ if (result.length <= 1) {
1681
+ console.log(chalk.yellow(`No dependents found for "${entityName}".`));
1682
+ console.log(chalk.dim(' This entity is not imported by any other known entities.'));
1683
+ console.log(chalk.dim(' Run codeyam editor analyze-imports to populate import data.'));
1684
+ return;
1685
+ }
1686
+ console.log(chalk.bold(`Dependency tree for ${entityName} (${result.length} entities):`));
1687
+ console.log();
1688
+ for (const entry of result) {
1689
+ const indent = ' '.repeat(entry.depth);
1690
+ const prefix = entry.depth === 0 ? chalk.cyan('●') : chalk.dim('├──');
1691
+ const label = entry.depth === 0
1692
+ ? chalk.cyan(`${entry.name} (changed)`)
1693
+ : chalk.white(entry.name);
1694
+ const type = chalk.dim(`[${entry.entityType}]`);
1695
+ console.log(`${indent}${prefix} ${label} ${type}`);
1696
+ }
1697
+ console.log();
1698
+ console.log(chalk.dim('All listed entities need their scenarios recaptured after changes.'));
1699
+ }
1700
+ // ─── Change subcommand ───────────────────────────────────────────────
1701
+ /**
1702
+ * `codeyam editor change <feature>`
1703
+ *
1704
+ * Prints a condensed post-change checklist that guides Claude through
1705
+ * re-verifying after user-requested modifications. This is the "change
1706
+ * loop" — it replaces the freeform "make changes" path with structured
1707
+ * instructions that always loop back to step 13 present.
1708
+ */
1709
+ function handleChange(feature) {
1710
+ const root = getProjectRoot();
1711
+ if (!feature) {
1712
+ // Try to read feature from state
1713
+ const state = readState(root);
1714
+ if (state?.feature) {
1715
+ feature = state.feature;
1716
+ }
1717
+ else {
1718
+ console.error(chalk.red('Error: Feature name required.'));
1719
+ console.error(chalk.dim(' Usage: codeyam editor change "My Feature"'));
1720
+ process.exit(1);
1721
+ }
1722
+ }
1723
+ const port = getServerPort();
1724
+ console.log();
1725
+ console.log(chalk.bold.cyan('━━━ Change Loop ━━━'));
1726
+ console.log(chalk.dim(`Feature: ${feature}`));
1727
+ console.log();
1728
+ console.log('The user has requested changes. Follow this checklist after making them.');
1729
+ console.log();
1730
+ console.log(chalk.bold.cyan('Keep the preview moving:'));
1731
+ console.log(chalk.cyan(` Refresh after EACH individual change — not after all changes are done:`));
1732
+ console.log(chalk.cyan(` codeyam editor preview`));
1733
+ console.log(chalk.cyan(' The user is watching the preview. Let them see progress incrementally.'));
1734
+ console.log();
1735
+ console.log(chalk.bold('0. Close the results panel:'));
1736
+ checkbox(`Hide results: \`codeyam editor hide-results\``);
1737
+ console.log();
1738
+ console.log(chalk.bold('1. Re-register affected component scenarios:'));
1739
+ checkbox('For each component you modified, re-register ALL its scenarios');
1740
+ console.log(chalk.dim(` codeyam editor register '{"name":"ComponentName - ScenarioName","componentName":"ComponentName","componentPath":"app/components/ComponentName.tsx","url":"/isolated-components/ComponentName?s=ScenarioName"}'`));
1741
+ checkbox('For any NEW components: `codeyam editor isolate NewComponent` then create isolation routes and register scenarios');
1742
+ console.log();
1743
+ console.log(chalk.bold('2. Re-run affected tests:'));
1744
+ checkbox('Re-run test files for any functions you modified');
1745
+ console.log(chalk.dim(' Example: npx vitest run app/lib/drinks.test.ts'));
1746
+ checkbox('If any test fails, fix the source code and re-run');
1747
+ checkbox('If you re-seeded the database, restart the dev server to pick up fresh data');
1748
+ console.log(chalk.dim(` codeyam editor dev-server '{"action":"restart"}'`));
1749
+ console.log();
1750
+ console.log(chalk.bold('3. Re-capture app-level scenarios:'));
1751
+ checkbox('Run `codeyam editor analyze-imports` to refresh the import graph after code changes');
1752
+ checkbox('For each changed component, run `codeyam editor dependents ComponentName` to find affected pages');
1753
+ checkbox('Run `codeyam editor scenarios` to list all existing scenarios');
1754
+ checkbox('For EACH page listed by dependents: find its existing scenarios in the list and re-register every one');
1755
+ console.log(chalk.dim(' Shared components (headers, navbars, layouts) affect MANY pages — re-register all of them.'));
1756
+ console.log(chalk.dim(' Re-register with the SAME name to update — do NOT create new/duplicate scenarios.'));
1757
+ console.log(chalk.dim(' Example: if Header changed and Home, Catalog, Detail pages use it,'));
1758
+ console.log(chalk.dim(' re-register "Home - Default", "Catalog - Full", "Detail - WithReviews", etc.'));
1759
+ console.log();
1760
+ console.log(chalk.bold('4. Verify completeness:'));
1761
+ checkbox(`Refresh the preview: \`codeyam editor preview\``);
1762
+ checkbox(`Navigate to key pages to verify changes: \`codeyam editor preview '{"path":"/your-route"}'\``);
1763
+ checkbox('Run `codeyam editor audit` — all checks must pass');
1764
+ checkbox(`Check for client-side errors: \`codeyam editor client-errors\``);
1765
+ console.log(chalk.dim(' If `hasContent=false`, the preview is blank — fix the code before proceeding.'));
1766
+ console.log(chalk.dim(' If `liveErrors>0`, there are JS errors in the preview — fix them.'));
1767
+ checkbox('Fix any errors, then re-register affected scenarios');
1768
+ console.log();
1769
+ console.log(chalk.bold('5. Update the existing journal entry:'));
1770
+ checkbox('Get existing entry: `codeyam editor journal-list`');
1771
+ checkbox('Find the uncommitted entry (commitSha is null) from this feature session');
1772
+ checkbox(`Update it: \`codeyam editor journal-update '{"time":"<entry time>","description":"<updated description including changes>","includeSessionScenarios":true}'\``);
1773
+ console.log(chalk.dim(' Always update the existing uncommitted entry — do NOT create a new one.'));
1774
+ console.log(chalk.dim(' Only create a new entry (POST) if no uncommitted entry exists for this feature.'));
1775
+ console.log();
1776
+ console.log(chalk.red(' ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'));
1777
+ console.log(chalk.red.bold(' REQUIRED: Show Results'));
1778
+ console.log(chalk.red.bold(' When all checks pass, you MUST run: ') +
1779
+ chalk.bold(`codeyam editor 13`));
1780
+ console.log(chalk.red.bold(' The user ALWAYS expects to see results after changes. DO NOT skip this step.'));
1781
+ console.log(chalk.red(' ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'));
1782
+ console.log();
1783
+ }
1784
+ // ─── Audit subcommand ────────────────────────────────────────────────
1785
+ /**
1786
+ * `codeyam editor audit`
1787
+ *
1788
+ * Fetches the /api/editor-audit endpoint and prints a checklist showing
1789
+ * which glossary components have registered scenarios and which functions
1790
+ * have test files. Exits with code 1 if anything is missing.
1791
+ */
1792
+ async function handleAudit() {
1793
+ const port = getServerPort();
1794
+ const url = `http://localhost:${port}/api/editor-audit`;
1795
+ let data;
1796
+ try {
1797
+ const res = await fetch(url);
1798
+ if (!res.ok) {
1799
+ console.error(chalk.red(`Error: Audit endpoint returned ${res.status}`));
1800
+ process.exit(1);
1801
+ }
1802
+ data = await res.json();
1803
+ }
1804
+ catch (err) {
1805
+ console.error(chalk.red('Error: Could not reach the CodeYam server. Is it running?'));
1806
+ console.error(chalk.dim(` ${err.message}`));
1807
+ process.exit(1);
1808
+ }
1809
+ const { components, functions, summary } = data;
1810
+ console.log();
1811
+ console.log(chalk.bold.cyan('━━━ Editor Audit ━━━'));
1812
+ console.log();
1813
+ // Components
1814
+ if (components.length > 0) {
1815
+ console.log(chalk.bold('Components (scenarios):'));
1816
+ for (const c of components) {
1817
+ const icon = c.status === 'ok' ? chalk.green('✓') : chalk.red('✗');
1818
+ let detail;
1819
+ if (c.status === 'has_errors') {
1820
+ detail = chalk.red(` — ${c.scenarioCount} scenario${c.scenarioCount !== 1 ? 's' : ''} but has client errors`);
1821
+ }
1822
+ else if (c.status === 'ok') {
1823
+ detail = chalk.dim(` (${c.scenarioCount} scenario${c.scenarioCount !== 1 ? 's' : ''})`);
1824
+ }
1825
+ else {
1826
+ detail = chalk.red(' — no scenarios registered');
1827
+ }
1828
+ console.log(` ${icon} ${c.name}${detail}`);
1829
+ if (c.clientErrors && c.clientErrors.length > 0) {
1830
+ for (const err of c.clientErrors.slice(0, 3)) {
1831
+ console.log(chalk.red(` → ${err}`));
1832
+ }
1833
+ if (c.clientErrors.length > 3) {
1834
+ console.log(chalk.dim(` … and ${c.clientErrors.length - 3} more`));
1835
+ }
1836
+ }
1837
+ }
1838
+ console.log();
1839
+ }
1840
+ // Functions
1841
+ if (functions.length > 0) {
1842
+ console.log(chalk.bold('Functions (test files):'));
1843
+ for (const f of functions) {
1844
+ const icon = f.status === 'ok' ? chalk.green('✓') : chalk.red('✗');
1845
+ let detail;
1846
+ switch (f.status) {
1847
+ case 'ok':
1848
+ detail = chalk.dim(` (${f.testFile})`);
1849
+ break;
1850
+ case 'failing':
1851
+ detail = chalk.red(` — tests failing: ${f.testFile}`);
1852
+ break;
1853
+ case 'name_mismatch':
1854
+ detail = chalk.red(` — tests pass but missing top-level describe("${f.name}", ...) — tests won't display in UI`);
1855
+ break;
1856
+ case 'missing':
1857
+ default:
1858
+ detail = f.testFile
1859
+ ? chalk.red(` — test file missing: ${f.testFile}`)
1860
+ : chalk.red(' — no test file specified');
1861
+ break;
1862
+ }
1863
+ console.log(` ${icon} ${f.name}${detail}`);
1864
+ }
1865
+ console.log();
1866
+ }
1867
+ // Summary
1868
+ const allOk = summary.allPassing;
1869
+ if (allOk) {
1870
+ console.log(chalk.green.bold('All checks passed!') +
1871
+ chalk.dim(` (${summary.totalComponents} component${summary.totalComponents !== 1 ? 's' : ''}, ${summary.totalFunctions} function${summary.totalFunctions !== 1 ? 's' : ''})`));
1872
+ }
1873
+ else {
1874
+ const parts = [];
1875
+ if (summary.componentsMissing > 0) {
1876
+ parts.push(`${summary.componentsMissing} component${summary.componentsMissing !== 1 ? 's' : ''} missing scenarios`);
1877
+ }
1878
+ if (summary.componentsWithErrors > 0) {
1879
+ parts.push(`${summary.componentsWithErrors} component${summary.componentsWithErrors !== 1 ? 's' : ''} with client errors`);
1880
+ }
1881
+ if (summary.functionsMissing > 0) {
1882
+ parts.push(`${summary.functionsMissing} function${summary.functionsMissing !== 1 ? 's' : ''} missing tests`);
1883
+ }
1884
+ if (summary.functionsFailing > 0) {
1885
+ parts.push(`${summary.functionsFailing} function${summary.functionsFailing !== 1 ? 's' : ''} with failing tests`);
1886
+ }
1887
+ if (summary.functionsNameMismatch > 0) {
1888
+ parts.push(`${summary.functionsNameMismatch} function${summary.functionsNameMismatch !== 1 ? 's' : ''} with test name mismatch (missing top-level describe)`);
1889
+ }
1890
+ console.log(chalk.red.bold('Audit failed: ') + parts.join(', '));
1891
+ }
1892
+ console.log();
1893
+ if (!allOk) {
1894
+ process.exit(1);
1895
+ }
1896
+ }
1897
+ // ─── Scenarios subcommand ─────────────────────────────────────────────
1898
+ async function handleScenarios() {
1899
+ const port = getServerPort();
1900
+ const url = `http://localhost:${port}/api/editor-scenarios`;
1901
+ let data;
1902
+ try {
1903
+ const res = await fetch(url);
1904
+ if (!res.ok) {
1905
+ console.error(chalk.red(`Error: Scenarios endpoint returned ${res.status}`));
1906
+ process.exit(1);
1907
+ }
1908
+ data = await res.json();
1909
+ }
1910
+ catch (err) {
1911
+ console.error(chalk.red('Error: Could not reach the CodeYam server. Is it running?'));
1912
+ console.error(chalk.dim(` ${err.message}`));
1913
+ process.exit(1);
1914
+ }
1915
+ const scenarios = data.scenarios;
1916
+ if (scenarios.length === 0) {
1917
+ console.log();
1918
+ console.log(chalk.yellow('No scenarios found for this feature session.'));
1919
+ console.log();
1920
+ return;
1921
+ }
1922
+ // Group by componentName (null → "Uncategorized")
1923
+ const groups = new Map();
1924
+ for (const s of scenarios) {
1925
+ const key = s.componentName || 'Uncategorized';
1926
+ if (!groups.has(key))
1927
+ groups.set(key, []);
1928
+ groups.get(key).push(s);
1929
+ }
1930
+ // Strip component prefix from names (e.g. "DrinkCard - Default" → "Default")
1931
+ function stripPrefix(name, componentName) {
1932
+ if (!componentName)
1933
+ return name;
1934
+ const prefix = `${componentName} - `;
1935
+ return name.startsWith(prefix) ? name.slice(prefix.length) : name;
1936
+ }
1937
+ // Calculate column widths
1938
+ let maxCompLen = 'Component'.length;
1939
+ let maxScenLen = 'Scenario'.length;
1940
+ for (const [comp, items] of groups) {
1941
+ maxCompLen = Math.max(maxCompLen, comp.length);
1942
+ for (const s of items) {
1943
+ const display = stripPrefix(s.name, s.componentName);
1944
+ maxScenLen = Math.max(maxScenLen, display.length);
1945
+ }
1946
+ }
1947
+ const pad = (str, len) => str + ' '.repeat(Math.max(0, len - str.length));
1948
+ // Build OSC 8 hyperlink (display length = visible text only)
1949
+ const osc8 = (url, text) => `\x1b]8;;${url}\x07${text}\x1b]8;;\x07`;
1950
+ // Print table
1951
+ console.log();
1952
+ console.log(chalk.bold.cyan('━━━ Scenario Table ━━━'));
1953
+ console.log();
1954
+ const divComp = '─'.repeat(maxCompLen + 2);
1955
+ const divScen = '─'.repeat(maxScenLen + 2);
1956
+ // Header
1957
+ console.log(`┌${divComp}┬${divScen}┐`);
1958
+ console.log(`│ ${chalk.bold(pad('Component', maxCompLen))} │ ${chalk.bold(pad('Scenario', maxScenLen))} │`);
1959
+ console.log(`├${divComp}┼${divScen}┤`);
1960
+ // Rows
1961
+ let groupIndex = 0;
1962
+ for (const [comp, items] of groups) {
1963
+ if (groupIndex > 0) {
1964
+ console.log(`├${divComp}┼${divScen}┤`);
1965
+ }
1966
+ for (let i = 0; i < items.length; i++) {
1967
+ const s = items[i];
1968
+ const compCell = i === 0 ? chalk.bold(pad(comp, maxCompLen)) : pad('', maxCompLen);
1969
+ const display = stripPrefix(s.name, s.componentName);
1970
+ const linked = osc8(s.link, display);
1971
+ // linked has invisible escape chars; pad based on display length
1972
+ const scenPad = ' '.repeat(Math.max(0, maxScenLen - display.length));
1973
+ console.log(`│ ${compCell} │ ${linked}${scenPad} │`);
1974
+ }
1975
+ groupIndex++;
1976
+ }
1977
+ // Footer
1978
+ console.log(`└${divComp}┴${divScen}┘`);
1979
+ console.log();
1980
+ const total = scenarios.length;
1981
+ const groupCount = groups.size;
1982
+ console.log(chalk.dim(`${total} scenario${total !== 1 ? 's' : ''} across ${groupCount} component${groupCount !== 1 ? 's' : ''}`));
1983
+ console.log();
1984
+ }
1985
+ // ─── Template subcommand ─────────────────────────────────────────────
1986
+ async function handleTemplate() {
1987
+ const root = getProjectRoot();
1988
+ const port = getServerPort();
1989
+ if (hasProject(root)) {
1990
+ console.log(chalk.yellow('Project already exists (package.json found). Skipping.'));
1991
+ return;
1992
+ }
1993
+ // Determine which template to use from editor state
1994
+ const state = readState(root);
1995
+ const techStackId = state?.techStackId;
1996
+ const stack = techStackId
1997
+ ? TECH_STACKS.find((s) => s.id === techStackId)
1998
+ : undefined;
1999
+ const templateName = stack?.templateDir || 'nextjs-prisma-sqlite';
2000
+ const templateDir = path.join(__dirname, '..', '..', 'templates', templateName);
2001
+ if (!fs.existsSync(templateDir)) {
2002
+ console.error(chalk.red('Error: Template directory not found at ' + templateDir));
2003
+ process.exit(1);
2004
+ }
2005
+ const { execSync } = await import('child_process');
2006
+ // 1. Copy template files
2007
+ console.log(chalk.bold(`Copying ${stack?.name || templateName} template files...`));
2008
+ execSync(`cp -r ${templateDir}/* .`, { cwd: root, stdio: 'inherit' });
2009
+ // Copy dotfiles that are stored without the dot prefix in templates
2010
+ const gitignorePath = path.join(templateDir, 'gitignore');
2011
+ if (fs.existsSync(gitignorePath)) {
2012
+ execSync(`cp ${templateDir}/gitignore .gitignore`, {
2013
+ cwd: root,
2014
+ stdio: 'inherit',
2015
+ });
2016
+ }
2017
+ const envPath = path.join(templateDir, 'env');
2018
+ if (fs.existsSync(envPath)) {
2019
+ execSync(`cp ${templateDir}/env .env`, { cwd: root, stdio: 'inherit' });
2020
+ }
2021
+ // Copy seed adapter into .codeyam/ (stored outside .codeyam/ in the template
2022
+ // to avoid gitignore issues — .codeyam/ is selectively ignored in user projects)
2023
+ const seedAdapterSrc = path.join(templateDir, 'seed-adapter.ts');
2024
+ if (fs.existsSync(seedAdapterSrc)) {
2025
+ const codeyamDir = path.join(root, '.codeyam');
2026
+ if (!fs.existsSync(codeyamDir)) {
2027
+ fs.mkdirSync(codeyamDir, { recursive: true });
2028
+ }
2029
+ fs.copyFileSync(seedAdapterSrc, path.join(codeyamDir, 'seed-adapter.ts'));
2030
+ }
2031
+ console.log(chalk.green(' Template files copied.'));
2032
+ // 2. Install dependencies
2033
+ console.log(chalk.bold('Installing dependencies...'));
2034
+ execSync('npm install', { cwd: root, stdio: 'inherit' });
2035
+ console.log(chalk.green(' Dependencies installed.'));
2036
+ // 3. Initialize git
2037
+ const hasGit = fs.existsSync(path.join(root, '.git'));
2038
+ if (!hasGit) {
2039
+ console.log(chalk.bold('Initializing git...'));
2040
+ execSync('git init && git add -A && git commit -m "Initial commit"', {
2041
+ cwd: root,
2042
+ stdio: 'inherit',
2043
+ });
2044
+ console.log(chalk.green(' Git initialized.'));
2045
+ }
2046
+ // 4. Run codeyam init
2047
+ console.log(chalk.bold('Running codeyam init...'));
2048
+ await initCommand.handler({
2049
+ force: true,
2050
+ 'keep-server': true,
2051
+ autoInit: false,
2052
+ $0: '',
2053
+ _: [],
2054
+ });
2055
+ console.log(chalk.green(' CodeYam initialized.'));
2056
+ // 5. Verify config has startCommand
2057
+ const configPath = path.join(root, '.codeyam', 'config.json');
2058
+ if (fs.existsSync(configPath)) {
2059
+ try {
2060
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
2061
+ const webapps = config.webapps || [];
2062
+ const hasStartCommand = webapps.some((w) => w.startCommand);
2063
+ if (!hasStartCommand) {
2064
+ console.log(chalk.yellow(' Warning: No startCommand found in .codeyam/config.json webapps.'));
2065
+ console.log(chalk.dim(' You may need to add: "startCommand": { "command": "sh", "args": ["-c", "npm run dev -- --port $PORT"] }'));
2066
+ }
2067
+ }
2068
+ catch {
2069
+ // Config parse error is non-fatal
2070
+ }
2071
+ }
2072
+ // 6. Trigger editor-refresh so the server picks up the new project
2073
+ console.log(chalk.bold('Refreshing editor...'));
2074
+ try {
2075
+ await fetch(`http://localhost:${port}/api/editor-refresh`, {
2076
+ method: 'POST',
2077
+ });
2078
+ console.log(chalk.green(' Editor refreshed.'));
2079
+ }
2080
+ catch {
2081
+ console.log(chalk.yellow(' Could not reach the CodeYam server for refresh. You may need to restart it.'));
2082
+ }
2083
+ console.log();
2084
+ console.log(chalk.green.bold('Project scaffolded and ready!'));
2085
+ console.log(chalk.dim('Next: Define your Prisma models, push the schema, seed the database, and build your feature.'));
2086
+ }
2087
+ // ─── Sync subcommand ─────────────────────────────────────────────────
2088
+ /**
2089
+ * `codeyam editor sync`
2090
+ * Import scenarios from scenarios-manifest.json into the local database.
2091
+ */
2092
+ async function handleSync() {
2093
+ const root = getProjectRoot();
2094
+ const manifest = readManifest(root);
2095
+ if (!manifest) {
2096
+ console.log(chalk.yellow('No scenarios-manifest.json found. Nothing to sync.'));
2097
+ return;
2098
+ }
2099
+ if (manifest.scenarios.length === 0) {
2100
+ console.log(chalk.dim('Manifest is empty. Nothing to sync.'));
2101
+ return;
2102
+ }
2103
+ const configPath = path.join(root, '.codeyam', 'config.json');
2104
+ let projectSlug = null;
2105
+ try {
2106
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
2107
+ projectSlug = config.projectSlug || null;
2108
+ }
2109
+ catch {
2110
+ // fall through
2111
+ }
2112
+ if (!projectSlug) {
2113
+ console.error(chalk.red('Error: No project slug found. Run codeyam init first.'));
2114
+ process.exit(1);
2115
+ }
2116
+ const connectionOk = await withoutSpinner(() => testEnvironment());
2117
+ if (!connectionOk) {
2118
+ errorLog('Environment validation failed');
2119
+ return;
2120
+ }
2121
+ const { project } = await requireBranchAndProject(projectSlug);
2122
+ const { getDatabase } = await import('../../../packages/database/index.js');
2123
+ const db = getDatabase();
2124
+ // Fetch existing editor scenarios
2125
+ const existingRows = await db
2126
+ .selectFrom('editor_scenarios')
2127
+ .select(['id', 'updated_at'])
2128
+ .where('project_id', '=', project.id)
2129
+ .execute();
2130
+ const result = await syncManifestToDatabase(root, project.id, existingRows, async (row) => {
2131
+ await db
2132
+ .insertInto('editor_scenarios')
2133
+ .values(row)
2134
+ .execute();
2135
+ }, async (id, row) => {
2136
+ await db
2137
+ .updateTable('editor_scenarios')
2138
+ .set(row)
2139
+ .where('id', '=', id)
2140
+ .execute();
2141
+ });
2142
+ if (result.inserted === 0 && result.updated === 0) {
2143
+ console.log(chalk.dim('All scenarios up to date.'));
2144
+ }
2145
+ else {
2146
+ const parts = [];
2147
+ if (result.inserted > 0)
2148
+ parts.push(`${result.inserted} imported`);
2149
+ if (result.updated > 0)
2150
+ parts.push(`${result.updated} updated`);
2151
+ if (result.skipped > 0)
2152
+ parts.push(`${result.skipped} unchanged`);
2153
+ console.log(chalk.green(`Synced scenarios: ${parts.join(', ')}`));
2154
+ }
2155
+ }
2156
+ // ─── Verify Images subcommand ─────────────────────────────────────────
2157
+ async function handleVerifyImages(jsonArg) {
2158
+ const port = getServerPort();
2159
+ const { parseVerifyImagesInput, extractImageUrls, resolveImageUrl, verifyImageUrls, buildVerifyImagesReport, extractImageUrlsFromScenarioFiles, } = await import('../utils/editorImageVerifier.js');
2160
+ let paths;
2161
+ let explicitImageUrls;
2162
+ try {
2163
+ const input = parseVerifyImagesInput(jsonArg);
2164
+ paths = input.paths;
2165
+ explicitImageUrls = input.imageUrls;
2166
+ }
2167
+ catch {
2168
+ console.error(chalk.red('Error: Invalid JSON argument'));
2169
+ process.exit(1);
2170
+ }
2171
+ // Get dev server URL
2172
+ let devServerUrl;
2173
+ try {
2174
+ const res = await fetch(`http://localhost:${port}/api/editor-dev-server`);
2175
+ const data = await res.json();
2176
+ devServerUrl = data.url || `http://localhost:${data.port || 3000}`;
2177
+ }
2178
+ catch {
2179
+ console.error(chalk.red('Error: Could not reach the CodeYam server. Is it running?'));
2180
+ process.exit(1);
2181
+ }
2182
+ const allUrls = new Set();
2183
+ let pagesChecked = 0;
2184
+ for (const pagePath of paths) {
2185
+ const pageUrl = `${devServerUrl}${pagePath}`;
2186
+ try {
2187
+ const res = await fetch(pageUrl);
2188
+ if (!res.ok) {
2189
+ console.error(chalk.red(` ✗ ${pagePath} — HTTP ${res.status}`));
2190
+ continue;
2191
+ }
2192
+ const html = await res.text();
2193
+ const imageUrls = extractImageUrls(html);
2194
+ for (const url of imageUrls) {
2195
+ allUrls.add(resolveImageUrl(url, devServerUrl));
2196
+ }
2197
+ pagesChecked++;
2198
+ }
2199
+ catch (err) {
2200
+ console.error(chalk.red(` ✗ ${pagePath} — ${err.message}`));
2201
+ }
2202
+ }
2203
+ // Add explicitly-provided image URLs (Claude passes these directly)
2204
+ for (const url of explicitImageUrls) {
2205
+ allUrls.add(resolveImageUrl(url, devServerUrl));
2206
+ }
2207
+ // Also scan scenario mock data files for image URLs (client-rendered pages)
2208
+ const scenariosDir = path.join(getProjectRoot(), '.codeyam', 'editor-scenarios');
2209
+ const { urls: scenarioUrls, filesScanned: scenarioFilesScanned } = extractImageUrlsFromScenarioFiles(scenariosDir);
2210
+ for (const url of scenarioUrls) {
2211
+ allUrls.add(resolveImageUrl(url, devServerUrl));
2212
+ }
2213
+ const urlList = [...allUrls];
2214
+ const results = urlList.length > 0 ? await verifyImageUrls(urlList) : [];
2215
+ const report = buildVerifyImagesReport({
2216
+ pagesChecked,
2217
+ imageUrls: urlList,
2218
+ results,
2219
+ scenarioFilesScanned,
2220
+ });
2221
+ console.log(JSON.stringify(report, null, 2));
2222
+ if (report.failures.length > 0) {
2223
+ process.exit(1);
2224
+ }
2225
+ }
2226
+ // ─── Debug subcommand ────────────────────────────────────────────────
2227
+ function handleEditorDebug(args) {
2228
+ const root = getProjectRoot();
2229
+ const feature = args.feature || 'Sample Feature';
2230
+ const includeContext = args.includeContext !== false;
2231
+ let targets;
2232
+ try {
2233
+ targets = parseDebugTargets(args.target);
2234
+ }
2235
+ catch (err) {
2236
+ const msg = err instanceof Error ? err.message : String(err);
2237
+ console.error(chalk.red(`Error: ${msg}`));
2238
+ process.exit(1);
2239
+ }
2240
+ const includeResume = typeof args.resume === 'boolean' ? args.resume : true;
2241
+ const includeNormal = typeof args.resume === 'boolean' ? !args.resume : true;
2242
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
2243
+ const outputDir = args.output
2244
+ ? path.resolve(args.output)
2245
+ : path.join(root, '.codeyam', 'logs', 'editor-debug', timestamp);
2246
+ fs.mkdirSync(outputDir, { recursive: true });
2247
+ const contextEntries = includeContext
2248
+ ? writeContextSnapshot(root, outputDir)
2249
+ : [];
2250
+ const scenarios = [];
2251
+ const wants = (id) => (targets ? targets.has(id) : true);
2252
+ if (wants('setup')) {
2253
+ scenarios.push({
2254
+ id: 'setup',
2255
+ title: 'Setup (no project)',
2256
+ render: () => withTempRoot(false, (tempRoot) => captureOutput(() => printSetup(tempRoot))),
2257
+ });
2258
+ }
2259
+ if (wants('overview')) {
2260
+ scenarios.push({
2261
+ id: 'overview',
2262
+ title: 'Cycle overview (project, no state)',
2263
+ render: () => withTempRoot(true, (tempRoot) => captureOutput(() => printCycleOverview(tempRoot, null))),
2264
+ });
2265
+ }
2266
+ if (wants('overview-with-state')) {
2267
+ scenarios.push({
2268
+ id: 'overview-with-state',
2269
+ title: 'Cycle overview (project, with state)',
2270
+ render: () => withTempRoot(true, (tempRoot) => captureOutput(() => printCycleOverview(tempRoot, makeState(4, feature)))),
2271
+ });
2272
+ }
2273
+ const stepFns = {
2274
+ 1: (r, f) => printStep1(r, f),
2275
+ 2: printStep2,
2276
+ 3: printStep3,
2277
+ 4: printStep4,
2278
+ 5: printStep5,
2279
+ 6: printStep6,
2280
+ 7: printStep7,
2281
+ 8: printStep8,
2282
+ 9: printStep9,
2283
+ 10: printStep10,
2284
+ 11: printStep11,
2285
+ 12: printStep12,
2286
+ 13: printStep13,
2287
+ };
2288
+ for (let step = 1; step <= 13; step++) {
2289
+ const stepId = `step-${step}`;
2290
+ if (!wants(stepId))
2291
+ continue;
2292
+ if (includeNormal) {
2293
+ scenarios.push({
2294
+ id: stepId,
2295
+ title: `Step ${step} (${STEP_LABELS[step]})`,
2296
+ render: () => withTempRoot(true, (tempRoot) => captureOutput(() => stepFns[step](tempRoot, feature))),
2297
+ });
2298
+ if (step === 1 && !args.feature) {
2299
+ scenarios.push({
2300
+ id: 'step-1-no-feature',
2301
+ title: 'Step 1 (Plan) — no feature provided',
2302
+ render: () => withTempRoot(true, (tempRoot) => captureOutput(() => printStep1(tempRoot, undefined))),
2303
+ });
2304
+ }
2305
+ if (step === 2) {
2306
+ scenarios.push({
2307
+ id: 'step-2-scaffold',
2308
+ title: 'Step 2 (Prototype) — scaffold flow (no project)',
2309
+ render: () => withTempRoot(false, (tempRoot) => captureOutput(() => printStep2(tempRoot, feature))),
2310
+ });
2311
+ }
2312
+ }
2313
+ if (includeResume) {
2314
+ scenarios.push({
2315
+ id: `${stepId}-resume`,
2316
+ title: `Step ${step} (${STEP_LABELS[step]}) — resuming`,
2317
+ render: () => withTempRoot(true, (tempRoot) => {
2318
+ writeState(tempRoot, makeState(step, feature));
2319
+ return captureOutput(() => stepFns[step](tempRoot, feature));
2320
+ }),
2321
+ });
2322
+ }
2323
+ }
2324
+ const indexLines = [
2325
+ '# CodeYam Editor Debug Bundle',
2326
+ '',
2327
+ `Generated: ${new Date().toISOString()}`,
2328
+ `Feature: "${feature}"`,
2329
+ `Resume variants: ${includeResume ? 'included' : 'skipped'}`,
2330
+ 'Note: Output files preserve ANSI color codes (as printed to the terminal).',
2331
+ '',
2332
+ ];
2333
+ if (includeContext) {
2334
+ indexLines.push('## Context snapshot');
2335
+ if (contextEntries.length === 0) {
2336
+ indexLines.push('- (none)');
2337
+ }
2338
+ else {
2339
+ for (const entry of contextEntries) {
2340
+ const source = entry.source ? ` ← ${entry.source}` : '';
2341
+ indexLines.push(`- ${entry.label}: ${entry.file} (${entry.status})${source}`);
2342
+ }
2343
+ }
2344
+ indexLines.push('');
2345
+ }
2346
+ indexLines.push('## Scenarios');
2347
+ for (const scenario of scenarios) {
2348
+ const fileName = `${scenario.id}.txt`;
2349
+ const output = scenario.render();
2350
+ fs.writeFileSync(path.join(outputDir, fileName), output, 'utf8');
2351
+ indexLines.push(`- ${scenario.title}: ${fileName}`);
2352
+ }
2353
+ fs.writeFileSync(path.join(outputDir, 'index.md'), indexLines.join('\n'), 'utf8');
2354
+ console.log();
2355
+ console.log(chalk.bold.cyan('━━━ Editor Debug Bundle ━━━'));
2356
+ console.log();
2357
+ console.log(chalk.green('Wrote debug bundle to: ') + chalk.bold(outputDir));
2358
+ console.log(chalk.dim(' Open index.md for the full list of scenario outputs.'));
618
2359
  console.log();
619
- console.log(chalk.dim('Do NOT skip the screenshot verification or user menu. Complete all phases in order.'));
620
- stopGate(10, { confirm: true });
621
2360
  }
622
2361
  // ─── Command definition ───────────────────────────────────────────────
623
2362
  const editorCommand = {
624
- command: 'editor [step]',
2363
+ command: 'editor [step] [json]',
625
2364
  describe: 'Editor mode guided workflow',
626
2365
  builder: (yargs) => {
627
- return yargs
2366
+ const stepDescription = IS_INTERNAL_BUILD
2367
+ ? 'Step number (1-13) or subcommand (template, register, isolate, analyze-imports, dependents, audit, scenarios, change, sync, debug, preview, show-results, hide-results, commit, journal, journal-list, journal-update, dev-server, client-errors)'
2368
+ : 'Step number (1-13) or subcommand (template, register, isolate, analyze-imports, dependents, audit, scenarios, change, sync, preview, show-results, hide-results, commit, journal, journal-list, journal-update, dev-server, client-errors)';
2369
+ let builder = yargs
628
2370
  .positional('step', {
629
- type: 'number',
630
- describe: 'Step number (1-10)',
631
- choices: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
2371
+ type: 'string',
2372
+ describe: stepDescription,
2373
+ })
2374
+ .positional('json', {
2375
+ type: 'string',
2376
+ describe: 'JSON argument for register subcommand',
632
2377
  })
633
2378
  .option('feature', {
634
2379
  type: 'string',
635
2380
  describe: 'Feature name (required for step 2)',
2381
+ })
2382
+ .option('app-formats', {
2383
+ type: 'string',
2384
+ describe: 'Comma-separated app formats (mobile-responsive-web-app, desktop-app, mobile-app)',
2385
+ })
2386
+ .option('tech-stack', {
2387
+ type: 'string',
2388
+ describe: 'Selected tech stack ID (e.g., nextjs-prisma-sqlite)',
2389
+ })
2390
+ .option('prompt', {
2391
+ type: 'string',
2392
+ describe: "User's original prompt (captured for journal/results)",
2393
+ })
2394
+ .option('port', {
2395
+ type: 'number',
2396
+ alias: 'p',
2397
+ describe: 'Port to run the web server on',
2398
+ default: 3111,
636
2399
  });
2400
+ if (IS_INTERNAL_BUILD) {
2401
+ builder = builder
2402
+ .option('target', {
2403
+ type: 'string',
2404
+ describe: 'Debug target (setup, overview, overview-with-state, step-1..step-13, or comma-separated list)',
2405
+ })
2406
+ .option('resume', {
2407
+ type: 'boolean',
2408
+ describe: 'Debug: only render resume variants (use --no-resume for only normal)',
2409
+ })
2410
+ .option('include-context', {
2411
+ type: 'boolean',
2412
+ default: true,
2413
+ describe: 'Debug: include CLAUDE.md, skill, and editor-mode-context snapshots',
2414
+ })
2415
+ .option('output', {
2416
+ type: 'string',
2417
+ describe: 'Debug: output directory for the bundle',
2418
+ });
2419
+ }
2420
+ return builder;
637
2421
  },
638
- handler: (argv) => {
2422
+ handler: async (argv) => {
639
2423
  const root = getProjectRoot();
640
- if (argv.step == null) {
641
- // No step specified: setup or overview
2424
+ // API subcommands: preview, show-results, hide-results, commit,
2425
+ // journal, journal-update, dev-server, client-errors
2426
+ if (argv.step && EDITOR_API_SUBCOMMANDS.includes(argv.step)) {
2427
+ const port = getServerPort();
2428
+ try {
2429
+ const request = buildEditorApiRequest(argv.step, argv.json || undefined);
2430
+ const result = await callEditorApi(request, port);
2431
+ if (!result.ok) {
2432
+ console.error(chalk.red(`Error: ${request.endpoint} returned ${result.status}`));
2433
+ if (result.data)
2434
+ console.error(JSON.stringify(result.data, null, 2));
2435
+ process.exit(1);
2436
+ }
2437
+ if (result.data != null) {
2438
+ const summary = formatApiSubcommandResult(argv.step, result.data);
2439
+ if (summary) {
2440
+ console.log(summary);
2441
+ }
2442
+ else {
2443
+ console.log(JSON.stringify(result.data, null, 2));
2444
+ }
2445
+ }
2446
+ }
2447
+ catch (err) {
2448
+ console.error(chalk.red('Error: Could not reach the CodeYam server. Is it running?'));
2449
+ console.error(chalk.dim(` ${err.message}`));
2450
+ process.exit(1);
2451
+ }
2452
+ return;
2453
+ }
2454
+ // Subcommand: codeyam editor register '{"name":"..."}'
2455
+ if (argv.step === 'register') {
2456
+ await handleRegister(argv.json || '');
2457
+ return;
2458
+ }
2459
+ // Subcommand: codeyam editor analyze-imports
2460
+ if (argv.step === 'analyze-imports') {
2461
+ await handleAnalyzeImports();
2462
+ return;
2463
+ }
2464
+ // Subcommand: codeyam editor dependents <EntityName>
2465
+ if (argv.step === 'dependents') {
2466
+ await handleDependents(argv.json || '');
2467
+ return;
2468
+ }
2469
+ // Subcommand: codeyam editor audit
2470
+ if (argv.step === 'audit') {
2471
+ await handleAudit();
2472
+ return;
2473
+ }
2474
+ // Subcommand: codeyam editor scenarios
2475
+ if (argv.step === 'scenarios') {
2476
+ await handleScenarios();
2477
+ return;
2478
+ }
2479
+ // Subcommand: codeyam editor change <feature>
2480
+ if (argv.step === 'change') {
2481
+ handleChange(argv.json || '');
2482
+ return;
2483
+ }
2484
+ // Subcommand: codeyam editor verify-images '{"paths":["/","/drinks/1"]}'
2485
+ if (argv.step === 'verify-images') {
2486
+ await handleVerifyImages(argv.json || '');
2487
+ return;
2488
+ }
2489
+ // Subcommand: codeyam editor validate-seed '{"products":[...]}'
2490
+ if (argv.step === 'validate-seed') {
2491
+ await handleValidateSeed(argv.json || '');
2492
+ return;
2493
+ }
2494
+ // Subcommand: codeyam editor isolate StarRating CategoryBadge DrinkCard
2495
+ if (argv.step === 'isolate') {
2496
+ const names = [];
2497
+ if (argv.json)
2498
+ names.push(...argv.json.split(/[\s,]+/).filter(Boolean));
2499
+ // Collect any extra positional args (yargs puts them in argv._)
2500
+ const extras = argv._.filter((a) => typeof a === 'string' && a !== 'editor');
2501
+ names.push(...extras);
2502
+ handleIsolate(names);
2503
+ return;
2504
+ }
2505
+ // Subcommand: codeyam editor template — scaffold project from template
2506
+ if (argv.step === 'template') {
2507
+ await handleTemplate();
2508
+ return;
2509
+ }
2510
+ // Subcommand: codeyam editor sync — import scenarios from manifest
2511
+ if (argv.step === 'sync') {
2512
+ await handleSync();
2513
+ return;
2514
+ }
2515
+ // Subcommand: codeyam editor debug [--target ...]
2516
+ if (argv.step === 'debug') {
2517
+ if (!IS_INTERNAL_BUILD) {
2518
+ console.error(chalk.red('Error: "codeyam editor debug" is internal-only.'));
2519
+ process.exit(1);
2520
+ }
2521
+ await handleEditorDebug(argv);
2522
+ return;
2523
+ }
2524
+ // Subcommand: codeyam editor steps — show setup or cycle overview
2525
+ if (argv.step === 'steps') {
642
2526
  if (!hasProject(root)) {
643
2527
  printSetup(root);
644
2528
  }
645
2529
  else {
646
2530
  const state = readState(root);
2531
+ // Clear prompt file when feature is done (step 13) so the hook
2532
+ // can capture the next feature request from the user.
2533
+ if (state?.step === 13) {
2534
+ clearEditorUserPrompt(root);
2535
+ }
647
2536
  printCycleOverview(root, state);
648
2537
  }
649
2538
  return;
650
2539
  }
2540
+ const step = argv.step ? parseInt(argv.step, 10) : undefined;
2541
+ if (step != null && (isNaN(step) || step < 1 || step > 13)) {
2542
+ console.error(chalk.red(`Error: Invalid step "${argv.step}". Must be 1-13.`));
2543
+ process.exit(1);
2544
+ }
2545
+ if (step == null) {
2546
+ // No step specified: launch editor server + open browser
2547
+ // Auto-init if needed
2548
+ let projectRoot = getStateProjectRoot();
2549
+ if (!projectRoot) {
2550
+ await initCommand.handler({
2551
+ force: false,
2552
+ autoInit: true,
2553
+ $0: '',
2554
+ _: [],
2555
+ });
2556
+ projectRoot = getStateProjectRoot();
2557
+ if (!projectRoot) {
2558
+ return;
2559
+ }
2560
+ }
2561
+ const configPath = path.join(projectRoot, '.codeyam', 'config.json');
2562
+ try {
2563
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
2564
+ const { projectSlug } = config;
2565
+ if (!projectSlug) {
2566
+ errorLog('Missing project slug. Try reinitializing with: codeyam init --force');
2567
+ return;
2568
+ }
2569
+ const connectionOk = await withoutSpinner(() => testEnvironment());
2570
+ if (!connectionOk) {
2571
+ errorLog('Environment validation failed');
2572
+ return;
2573
+ }
2574
+ const { project, branch } = await requireBranchAndProject(projectSlug);
2575
+ // Auto-sync scenarios from manifest if it exists
2576
+ const manifestData = readManifest(projectRoot);
2577
+ if (manifestData && manifestData.scenarios.length > 0) {
2578
+ try {
2579
+ const { getDatabase } = await import('../../../packages/database/index.js');
2580
+ const db = getDatabase();
2581
+ const existingRows = await db
2582
+ .selectFrom('editor_scenarios')
2583
+ .select(['id', 'updated_at'])
2584
+ .where('project_id', '=', project.id)
2585
+ .execute();
2586
+ const syncResult = await syncManifestToDatabase(projectRoot, project.id, existingRows, async (row) => {
2587
+ await db
2588
+ .insertInto('editor_scenarios')
2589
+ .values(row)
2590
+ .execute();
2591
+ }, async (id, row) => {
2592
+ await db
2593
+ .updateTable('editor_scenarios')
2594
+ .set(row)
2595
+ .where('id', '=', id)
2596
+ .execute();
2597
+ });
2598
+ if (syncResult.inserted > 0 || syncResult.updated > 0) {
2599
+ const parts = [];
2600
+ if (syncResult.inserted > 0)
2601
+ parts.push(`${syncResult.inserted} imported`);
2602
+ if (syncResult.updated > 0)
2603
+ parts.push(`${syncResult.updated} updated`);
2604
+ console.log(chalk.green(` Synced scenarios from manifest: ${parts.join(', ')}`));
2605
+ }
2606
+ }
2607
+ catch {
2608
+ // Non-fatal — sync failure shouldn't block editor startup
2609
+ }
2610
+ }
2611
+ // `codeyam editor` (no step) always implies editor mode.
2612
+ // The empty-folder heuristic is no longer needed here — running this
2613
+ // command IS the signal. We still detect empty folders so that
2614
+ // the very first `codeyam editor` in a bare directory works before
2615
+ // metadata has been persisted.
2616
+ const editorMode = true;
2617
+ if (editorMode && !project.metadata?.labs?.simulations) {
2618
+ try {
2619
+ await updateProjectMetadata({
2620
+ projectSlug,
2621
+ metadataUpdate: {
2622
+ editorMode: true,
2623
+ labs: { simulations: true },
2624
+ },
2625
+ });
2626
+ const refreshed = await requireBranchAndProject(projectSlug);
2627
+ Object.assign(project, refreshed.project);
2628
+ }
2629
+ catch {
2630
+ // Non-fatal
2631
+ }
2632
+ }
2633
+ // Install skills/hooks
2634
+ const simulationsEnabled = project.metadata?.labs?.simulations ?? false;
2635
+ const skillMode = simulationsEnabled
2636
+ ? 'full'
2637
+ : editorMode
2638
+ ? 'editor'
2639
+ : 'memory';
2640
+ await installClaudeCodeSkills(projectRoot, {
2641
+ mode: skillMode,
2642
+ editorMode,
2643
+ });
2644
+ setupClaudeCodeSettings(projectRoot, {
2645
+ mode: skillMode,
2646
+ editorMode,
2647
+ });
2648
+ // Auto-finalize analyzer so codeyam analyze works
2649
+ if (editorMode && !isAnalyzerFinalized()) {
2650
+ try {
2651
+ const { execSync } = await import('child_process');
2652
+ const templatePath = getAnalyzerTemplatePath();
2653
+ if (fs.existsSync(templatePath)) {
2654
+ console.log(' Setting up simulations (first time only)...');
2655
+ execSync('npm install --include=dev', {
2656
+ cwd: templatePath,
2657
+ stdio: 'pipe',
2658
+ });
2659
+ execSync('npx playwright install chromium', {
2660
+ cwd: templatePath,
2661
+ stdio: 'pipe',
2662
+ });
2663
+ execSync('npm run build', {
2664
+ cwd: templatePath,
2665
+ stdio: 'pipe',
2666
+ });
2667
+ fs.writeFileSync(path.join(templatePath, '.finalized'), new Date().toISOString());
2668
+ }
2669
+ }
2670
+ catch {
2671
+ // Non-fatal
2672
+ }
2673
+ }
2674
+ // Start background server (handles killing existing servers internally)
2675
+ const editorPort = argv.port || 3111;
2676
+ const { url } = await startBackgroundServer({
2677
+ port: editorPort,
2678
+ rootPath: projectRoot,
2679
+ project,
2680
+ branch,
2681
+ });
2682
+ console.log();
2683
+ console.log(` Dashboard: ${url}`);
2684
+ console.log(' Run "codeyam --help" for all commands');
2685
+ console.log(chalk.bold(' Run "codeyam editor" to launch the editor at any time'));
2686
+ console.log();
2687
+ // Open browser to /editor
2688
+ try {
2689
+ const { execSync } = await import('child_process');
2690
+ const openCommand = process.platform === 'darwin'
2691
+ ? 'open'
2692
+ : process.platform === 'win32'
2693
+ ? 'start ""'
2694
+ : 'xdg-open';
2695
+ execSync(`${openCommand} "${url}/editor"`, { stdio: 'ignore' });
2696
+ }
2697
+ catch {
2698
+ // Silently fail if open command doesn't work
2699
+ }
2700
+ }
2701
+ catch (err) {
2702
+ errorLog('Failed to start CodeYam editor server');
2703
+ errorLog(err);
2704
+ process.exit(1);
2705
+ }
2706
+ return;
2707
+ }
651
2708
  const state = readState(root);
652
- switch (argv.step) {
653
- case 1:
654
- printStep1(root);
2709
+ switch (step) {
2710
+ case 1: {
2711
+ const feature = argv.feature || undefined;
2712
+ const appFormats = argv['app-formats']
2713
+ ? argv['app-formats'].split(',').map((f) => f.trim())
2714
+ : undefined;
2715
+ const techStackId = argv['tech-stack'] || undefined;
2716
+ const prompt = argv.prompt || undefined;
2717
+ printStep1(root, feature, { appFormats, techStackId }, prompt);
655
2718
  break;
2719
+ }
656
2720
  case 2: {
657
2721
  const feature = argv.feature || state?.feature;
658
2722
  if (!feature) {
@@ -670,7 +2734,10 @@ const editorCommand = {
670
2734
  case 7:
671
2735
  case 8:
672
2736
  case 9:
673
- case 10: {
2737
+ case 10:
2738
+ case 11:
2739
+ case 12:
2740
+ case 13: {
674
2741
  const feature = argv.feature || state?.feature;
675
2742
  if (!feature) {
676
2743
  console.error(chalk.red('Error: No feature in progress. Run codeyam editor 1 first.'));
@@ -685,8 +2752,11 @@ const editorCommand = {
685
2752
  8: printStep8,
686
2753
  9: printStep9,
687
2754
  10: printStep10,
2755
+ 11: printStep11,
2756
+ 12: printStep12,
2757
+ 13: printStep13,
688
2758
  };
689
- stepFns[argv.step](root, feature);
2759
+ stepFns[step](root, feature);
690
2760
  break;
691
2761
  }
692
2762
  }