@codeyam/codeyam-cli 0.1.8 → 0.1.9

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 (335) hide show
  1. package/analyzer-template/.build-info.json +8 -8
  2. package/analyzer-template/log.txt +3 -3
  3. package/analyzer-template/package.json +4 -4
  4. package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +0 -33
  5. package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +13 -7
  6. package/analyzer-template/packages/analyze/src/lib/asts/index.ts +7 -2
  7. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +0 -98
  8. package/analyzer-template/packages/aws/package.json +1 -1
  9. package/analyzer-template/packages/database/src/lib/kysely/tables/editorScenariosTable.ts +31 -0
  10. package/analyzer-template/packages/database/src/lib/loadEntities.ts +0 -6
  11. package/analyzer-template/packages/database/src/lib/updateCommitMetadata.ts +0 -65
  12. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts +5 -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 +31 -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/database/src/lib/loadEntities.d.ts.map +1 -1
  17. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js +0 -6
  18. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js.map +1 -1
  19. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts.map +1 -1
  20. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js +0 -25
  21. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js.map +1 -1
  22. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.d.ts +2 -0
  23. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.d.ts.map +1 -1
  24. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.js +2 -0
  25. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.js.map +1 -1
  26. package/analyzer-template/packages/types/src/enums/ProjectFramework.ts +2 -0
  27. package/analyzer-template/packages/ui-components/package.json +1 -1
  28. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.d.ts +2 -0
  29. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.d.ts.map +1 -1
  30. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.js +2 -0
  31. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.js.map +1 -1
  32. package/codeyam-cli/src/__tests__/memory-scripts/filter-session.test.js +196 -0
  33. package/codeyam-cli/src/__tests__/memory-scripts/filter-session.test.js.map +1 -0
  34. package/codeyam-cli/src/__tests__/memory-scripts/read-json-field.test.js +114 -0
  35. package/codeyam-cli/src/__tests__/memory-scripts/read-json-field.test.js.map +1 -0
  36. package/codeyam-cli/src/__tests__/memory-scripts/ripgrep-fallback.test.js +149 -0
  37. package/codeyam-cli/src/__tests__/memory-scripts/ripgrep-fallback.test.js.map +1 -0
  38. package/codeyam-cli/src/commands/__tests__/editor.stepDispatch.test.js +45 -0
  39. package/codeyam-cli/src/commands/__tests__/editor.stepDispatch.test.js.map +1 -0
  40. package/codeyam-cli/src/commands/__tests__/init.gitignore.test.js +101 -47
  41. package/codeyam-cli/src/commands/__tests__/init.gitignore.test.js.map +1 -1
  42. package/codeyam-cli/src/commands/default.js +3 -46
  43. package/codeyam-cli/src/commands/default.js.map +1 -1
  44. package/codeyam-cli/src/commands/editor.js +1619 -243
  45. package/codeyam-cli/src/commands/editor.js.map +1 -1
  46. package/codeyam-cli/src/commands/init.js +67 -34
  47. package/codeyam-cli/src/commands/init.js.map +1 -1
  48. package/codeyam-cli/src/data/techStacks.js +77 -0
  49. package/codeyam-cli/src/data/techStacks.js.map +1 -0
  50. package/codeyam-cli/src/utils/__tests__/analyzerFinalization.test.js +144 -0
  51. package/codeyam-cli/src/utils/__tests__/analyzerFinalization.test.js.map +1 -0
  52. package/codeyam-cli/src/utils/__tests__/backgroundServer.test.js +46 -0
  53. package/codeyam-cli/src/utils/__tests__/backgroundServer.test.js.map +1 -0
  54. package/codeyam-cli/src/utils/__tests__/devServerState.test.js +134 -0
  55. package/codeyam-cli/src/utils/__tests__/devServerState.test.js.map +1 -0
  56. package/codeyam-cli/src/utils/__tests__/editorApi.test.js +127 -0
  57. package/codeyam-cli/src/utils/__tests__/editorApi.test.js.map +1 -0
  58. package/codeyam-cli/src/utils/__tests__/editorAudit.test.js +610 -1
  59. package/codeyam-cli/src/utils/__tests__/editorAudit.test.js.map +1 -1
  60. package/codeyam-cli/src/utils/__tests__/editorCapture.test.js +93 -0
  61. package/codeyam-cli/src/utils/__tests__/editorCapture.test.js.map +1 -0
  62. package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js +181 -3
  63. package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js.map +1 -1
  64. package/codeyam-cli/src/utils/__tests__/editorEntityChangeStatus.test.js +121 -0
  65. package/codeyam-cli/src/utils/__tests__/editorEntityChangeStatus.test.js.map +1 -0
  66. package/codeyam-cli/src/utils/__tests__/editorImageVerifier.test.js +294 -0
  67. package/codeyam-cli/src/utils/__tests__/editorImageVerifier.test.js.map +1 -0
  68. package/codeyam-cli/src/utils/__tests__/editorJournal.test.js +249 -2
  69. package/codeyam-cli/src/utils/__tests__/editorJournal.test.js.map +1 -1
  70. package/codeyam-cli/src/utils/__tests__/editorLoaderHelpers.test.js +520 -0
  71. package/codeyam-cli/src/utils/__tests__/editorLoaderHelpers.test.js.map +1 -0
  72. package/codeyam-cli/src/utils/__tests__/editorPreloadHelpers.test.js +118 -1
  73. package/codeyam-cli/src/utils/__tests__/editorPreloadHelpers.test.js.map +1 -1
  74. package/codeyam-cli/src/utils/__tests__/editorPreview.test.js +195 -3
  75. package/codeyam-cli/src/utils/__tests__/editorPreview.test.js.map +1 -1
  76. package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js +153 -0
  77. package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js.map +1 -0
  78. package/codeyam-cli/src/utils/__tests__/editorScenarioLookup.test.js +139 -0
  79. package/codeyam-cli/src/utils/__tests__/editorScenarioLookup.test.js.map +1 -0
  80. package/codeyam-cli/src/utils/__tests__/editorScenarioSwitch.test.js +221 -0
  81. package/codeyam-cli/src/utils/__tests__/editorScenarioSwitch.test.js.map +1 -0
  82. package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js +781 -2
  83. package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js.map +1 -1
  84. package/codeyam-cli/src/utils/__tests__/editorSeedAdapter.test.js +213 -0
  85. package/codeyam-cli/src/utils/__tests__/editorSeedAdapter.test.js.map +1 -0
  86. package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js +1742 -0
  87. package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js.map +1 -0
  88. package/codeyam-cli/src/utils/__tests__/journalCaptureStabilization.test.js +107 -0
  89. package/codeyam-cli/src/utils/__tests__/journalCaptureStabilization.test.js.map +1 -0
  90. package/codeyam-cli/src/utils/__tests__/parseRegisterArg.test.js +101 -0
  91. package/codeyam-cli/src/utils/__tests__/parseRegisterArg.test.js.map +1 -0
  92. package/codeyam-cli/src/utils/__tests__/scenarioCoverage.test.js +227 -0
  93. package/codeyam-cli/src/utils/__tests__/scenarioCoverage.test.js.map +1 -0
  94. package/codeyam-cli/src/utils/__tests__/scenariosManifest.test.js +300 -0
  95. package/codeyam-cli/src/utils/__tests__/scenariosManifest.test.js.map +1 -0
  96. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +25 -5
  97. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  98. package/codeyam-cli/src/utils/__tests__/templateConsistency.test.js +51 -0
  99. package/codeyam-cli/src/utils/__tests__/templateConsistency.test.js.map +1 -0
  100. package/codeyam-cli/src/utils/__tests__/webappDetection.test.js +142 -0
  101. package/codeyam-cli/src/utils/__tests__/webappDetection.test.js.map +1 -0
  102. package/codeyam-cli/src/utils/analyzer.js +9 -0
  103. package/codeyam-cli/src/utils/analyzer.js.map +1 -1
  104. package/codeyam-cli/src/utils/analyzerFinalization.js +96 -0
  105. package/codeyam-cli/src/utils/analyzerFinalization.js.map +1 -0
  106. package/codeyam-cli/src/utils/backgroundServer.js +94 -18
  107. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  108. package/codeyam-cli/src/utils/database.js +37 -2
  109. package/codeyam-cli/src/utils/database.js.map +1 -1
  110. package/codeyam-cli/src/utils/devServerState.js +71 -0
  111. package/codeyam-cli/src/utils/devServerState.js.map +1 -0
  112. package/codeyam-cli/src/utils/editorApi.js +73 -0
  113. package/codeyam-cli/src/utils/editorApi.js.map +1 -0
  114. package/codeyam-cli/src/utils/editorAudit.js +101 -7
  115. package/codeyam-cli/src/utils/editorAudit.js.map +1 -1
  116. package/codeyam-cli/src/utils/editorCapture.js +102 -0
  117. package/codeyam-cli/src/utils/editorCapture.js.map +1 -0
  118. package/codeyam-cli/src/utils/editorDevServer.js +100 -1
  119. package/codeyam-cli/src/utils/editorDevServer.js.map +1 -1
  120. package/codeyam-cli/src/utils/editorEntityChangeStatus.js +44 -0
  121. package/codeyam-cli/src/utils/editorEntityChangeStatus.js.map +1 -0
  122. package/codeyam-cli/src/utils/editorImageVerifier.js +155 -0
  123. package/codeyam-cli/src/utils/editorImageVerifier.js.map +1 -0
  124. package/codeyam-cli/src/utils/editorJournal.js +92 -4
  125. package/codeyam-cli/src/utils/editorJournal.js.map +1 -1
  126. package/codeyam-cli/src/utils/editorLoaderHelpers.js +113 -0
  127. package/codeyam-cli/src/utils/editorLoaderHelpers.js.map +1 -0
  128. package/codeyam-cli/src/utils/editorMockState.js +1 -1
  129. package/codeyam-cli/src/utils/editorPreloadHelpers.js +72 -1
  130. package/codeyam-cli/src/utils/editorPreloadHelpers.js.map +1 -1
  131. package/codeyam-cli/src/utils/editorPreview.js +67 -1
  132. package/codeyam-cli/src/utils/editorPreview.js.map +1 -1
  133. package/codeyam-cli/src/utils/editorScenarioSwitch.js +112 -0
  134. package/codeyam-cli/src/utils/editorScenarioSwitch.js.map +1 -0
  135. package/codeyam-cli/src/utils/editorScenarios.js +276 -0
  136. package/codeyam-cli/src/utils/editorScenarios.js.map +1 -1
  137. package/codeyam-cli/src/utils/editorSeedAdapter.js +173 -0
  138. package/codeyam-cli/src/utils/editorSeedAdapter.js.map +1 -0
  139. package/codeyam-cli/src/utils/entityChangeStatus.js +349 -0
  140. package/codeyam-cli/src/utils/entityChangeStatus.js.map +1 -0
  141. package/codeyam-cli/src/utils/entityChangeStatus.server.js +158 -0
  142. package/codeyam-cli/src/utils/entityChangeStatus.server.js.map +1 -0
  143. package/codeyam-cli/src/utils/install-skills.js +1 -1
  144. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  145. package/codeyam-cli/src/utils/parseRegisterArg.js +31 -0
  146. package/codeyam-cli/src/utils/parseRegisterArg.js.map +1 -0
  147. package/codeyam-cli/src/utils/scenarioCoverage.js +75 -0
  148. package/codeyam-cli/src/utils/scenarioCoverage.js.map +1 -0
  149. package/codeyam-cli/src/utils/scenariosManifest.js +159 -0
  150. package/codeyam-cli/src/utils/scenariosManifest.js.map +1 -0
  151. package/codeyam-cli/src/utils/serverState.js +30 -0
  152. package/codeyam-cli/src/utils/serverState.js.map +1 -1
  153. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +46 -16
  154. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  155. package/codeyam-cli/src/utils/simulationGateMiddleware.js +8 -1
  156. package/codeyam-cli/src/utils/simulationGateMiddleware.js.map +1 -1
  157. package/codeyam-cli/src/utils/slugUtils.js +25 -0
  158. package/codeyam-cli/src/utils/slugUtils.js.map +1 -0
  159. package/codeyam-cli/src/utils/syncMocksMiddleware.js +2 -2
  160. package/codeyam-cli/src/utils/syncMocksMiddleware.js.map +1 -1
  161. package/codeyam-cli/src/utils/webappDetection.js +21 -0
  162. package/codeyam-cli/src/utils/webappDetection.js.map +1 -1
  163. package/codeyam-cli/src/webserver/__tests__/clientErrors.test.js +40 -0
  164. package/codeyam-cli/src/webserver/__tests__/clientErrors.test.js.map +1 -0
  165. package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js +567 -0
  166. package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js.map +1 -0
  167. package/codeyam-cli/src/webserver/app/lib/clientErrors.js +65 -0
  168. package/codeyam-cli/src/webserver/app/lib/clientErrors.js.map +1 -0
  169. package/codeyam-cli/src/webserver/app/lib/git.js +397 -0
  170. package/codeyam-cli/src/webserver/app/lib/git.js.map +1 -0
  171. package/codeyam-cli/src/webserver/build/client/assets/{CopyButton-DmJveP3T.js → CopyButton-BPXZwM4t.js} +1 -1
  172. package/codeyam-cli/src/webserver/build/client/assets/{EntityItem-C76mRRiF.js → EntityItem-BcgbViKV.js} +3 -3
  173. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeIcon-CobE682z.js → EntityTypeIcon-CQIG2qda.js} +9 -9
  174. package/codeyam-cli/src/webserver/build/client/assets/{ReportIssueModal-djPLI-WV.js → ReportIssueModal-BzHcG7SE.js} +3 -3
  175. package/codeyam-cli/src/webserver/build/client/assets/{ScenarioViewer-B76aig_2.js → ScenarioViewer-Bd-hxofb.js} +3 -3
  176. package/codeyam-cli/src/webserver/build/client/assets/ViewportInspectBar-oAf2Kqsf.js +1 -0
  177. package/codeyam-cli/src/webserver/build/client/assets/{_index-C96V0n15.js → _index-DLxKhri3.js} +3 -3
  178. package/codeyam-cli/src/webserver/build/client/assets/{activity.(_tab)-BpKzcsJz.js → activity.(_tab)-BcY3q6nt.js} +6 -6
  179. package/codeyam-cli/src/webserver/build/client/assets/addon-canvas-DpzMmAy5.js +1 -0
  180. package/codeyam-cli/src/webserver/build/client/assets/addon-fit-YJmn1quW.js +12 -0
  181. package/codeyam-cli/src/webserver/build/client/assets/addon-webgl-DI8QOUvO.js +58 -0
  182. package/codeyam-cli/src/webserver/build/client/assets/{agent-transcripts-D9hemwl6.js → agent-transcripts-Bni3iiUj.js} +5 -5
  183. package/codeyam-cli/src/webserver/build/client/assets/api.editor-file-diff-l0sNRNKZ.js +1 -0
  184. package/codeyam-cli/src/webserver/build/client/assets/api.editor-file-l0sNRNKZ.js +1 -0
  185. package/codeyam-cli/src/webserver/build/client/assets/api.editor-project-info-l0sNRNKZ.js +1 -0
  186. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-coverage-l0sNRNKZ.js +1 -0
  187. package/codeyam-cli/src/webserver/build/client/assets/{book-open-D_nMCFmP.js → book-open-BYOypzCa.js} +2 -2
  188. package/codeyam-cli/src/webserver/build/client/assets/{chevron-down-BH2h1Ea2.js → chevron-down-C_Pmso5S.js} +2 -2
  189. package/codeyam-cli/src/webserver/build/client/assets/{circle-check-DyIKORY6.js → circle-check-BVMi9VA5.js} +2 -2
  190. package/codeyam-cli/src/webserver/build/client/assets/{copy-NDbZjXao.js → copy-n2FB0_Sw.js} +3 -3
  191. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CC6AbExI.js +41 -0
  192. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-BsDh6TSF.js +1 -0
  193. package/codeyam-cli/src/webserver/build/client/assets/editor-PBc_6L9R.js +10 -0
  194. package/codeyam-cli/src/webserver/build/client/assets/editorPreview-4FzHlcNn.js +41 -0
  195. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-CrjR3zZW.js → entity._sha._-BsDXNp45.js} +3 -3
  196. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.dev-BgAqUtTZ.js +6 -0
  197. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-Bmshgrij.js +6 -0
  198. package/codeyam-cli/src/webserver/build/client/assets/{files-DO4CZ16O.js → files-BZrlFE1F.js} +1 -1
  199. package/codeyam-cli/src/webserver/build/client/assets/git-DdZcvjGh.js +1 -0
  200. package/codeyam-cli/src/webserver/build/client/assets/globals-B8vTTNy2.css +1 -0
  201. package/codeyam-cli/src/webserver/build/client/assets/index-yHOVb4rc.js +15 -0
  202. package/codeyam-cli/src/webserver/build/client/assets/{loader-circle-BAXYRVEO.js → loader-circle-DaAZ_H2w.js} +2 -2
  203. package/codeyam-cli/src/webserver/build/client/assets/manifest-65850841.js +1 -0
  204. package/codeyam-cli/src/webserver/build/client/assets/memory-9gnxSZlb.js +101 -0
  205. package/codeyam-cli/src/webserver/build/client/assets/{pause-DTAcYxBt.js → pause-f5-1lKBt.js} +3 -3
  206. package/codeyam-cli/src/webserver/build/client/assets/root-BwX8YgFb.js +67 -0
  207. package/codeyam-cli/src/webserver/build/client/assets/{search-fKo7v0Zo.js → search-Di64LWVb.js} +2 -2
  208. package/codeyam-cli/src/webserver/build/client/assets/{settings-DfuTtcJP.js → settings-0OrEMU6J.js} +1 -1
  209. package/codeyam-cli/src/webserver/build/client/assets/{simulations-B3aOzpCZ.js → simulations-DWT-CvLy.js} +1 -1
  210. package/codeyam-cli/src/webserver/build/client/assets/{terminal-BG4heKCG.js → terminal-Br7MOqts.js} +3 -3
  211. package/codeyam-cli/src/webserver/build/client/assets/{triangle-alert-DtSmdtM4.js → triangle-alert-BLdiCuG-.js} +2 -2
  212. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-BE43Hjti.js +1 -0
  213. package/codeyam-cli/src/webserver/build/server/assets/index-DEEQf4pi.js +1 -0
  214. package/codeyam-cli/src/webserver/build/server/assets/init-CkWmyFY2.js +10 -0
  215. package/codeyam-cli/src/webserver/build/server/assets/server-build-BHi-9O8W.js +439 -0
  216. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  217. package/codeyam-cli/src/webserver/build-info.json +5 -5
  218. package/codeyam-cli/src/webserver/editorProxy.js +487 -50
  219. package/codeyam-cli/src/webserver/editorProxy.js.map +1 -1
  220. package/codeyam-cli/src/webserver/scripts/codeyam-preload.mjs +242 -3
  221. package/codeyam-cli/src/webserver/scripts/journalCapture.ts +94 -4
  222. package/codeyam-cli/src/webserver/server.js +46 -14
  223. package/codeyam-cli/src/webserver/server.js.map +1 -1
  224. package/codeyam-cli/src/webserver/terminalServer.js +39 -11
  225. package/codeyam-cli/src/webserver/terminalServer.js.map +1 -1
  226. package/codeyam-cli/templates/chrome-extension-react/EXTENSION_SETUP.md +75 -0
  227. package/codeyam-cli/templates/chrome-extension-react/README.md +46 -0
  228. package/codeyam-cli/templates/chrome-extension-react/gitignore +15 -0
  229. package/codeyam-cli/templates/chrome-extension-react/index.html +12 -0
  230. package/codeyam-cli/templates/chrome-extension-react/package.json +27 -0
  231. package/codeyam-cli/templates/chrome-extension-react/popup.html +12 -0
  232. package/codeyam-cli/templates/chrome-extension-react/public/manifest.json +15 -0
  233. package/codeyam-cli/templates/chrome-extension-react/src/background/service-worker.ts +7 -0
  234. package/codeyam-cli/templates/chrome-extension-react/src/globals.css +6 -0
  235. package/codeyam-cli/templates/chrome-extension-react/src/lib/storage.ts +37 -0
  236. package/codeyam-cli/templates/chrome-extension-react/src/popup/App.tsx +12 -0
  237. package/codeyam-cli/templates/chrome-extension-react/src/popup/main.tsx +10 -0
  238. package/codeyam-cli/templates/chrome-extension-react/tsconfig.json +24 -0
  239. package/codeyam-cli/templates/chrome-extension-react/vite.config.ts +41 -0
  240. package/codeyam-cli/templates/codeyam-editor-claude.md +84 -5
  241. package/codeyam-cli/templates/editor-step-hook.py +97 -8
  242. package/codeyam-cli/templates/expo-react-native/MOBILE_SETUP.md +89 -0
  243. package/codeyam-cli/templates/expo-react-native/README.md +41 -0
  244. package/codeyam-cli/templates/expo-react-native/app/(tabs)/_layout.tsx +33 -0
  245. package/codeyam-cli/templates/expo-react-native/app/(tabs)/index.tsx +12 -0
  246. package/codeyam-cli/templates/expo-react-native/app/(tabs)/settings.tsx +12 -0
  247. package/codeyam-cli/templates/expo-react-native/app/_layout.tsx +12 -0
  248. package/codeyam-cli/templates/expo-react-native/app.json +18 -0
  249. package/codeyam-cli/templates/expo-react-native/babel.config.js +9 -0
  250. package/codeyam-cli/templates/expo-react-native/gitignore +12 -0
  251. package/codeyam-cli/templates/expo-react-native/global.css +3 -0
  252. package/codeyam-cli/templates/expo-react-native/lib/storage.ts +32 -0
  253. package/codeyam-cli/templates/expo-react-native/metro.config.js +6 -0
  254. package/codeyam-cli/templates/expo-react-native/nativewind-env.d.ts +1 -0
  255. package/codeyam-cli/templates/expo-react-native/package.json +38 -0
  256. package/codeyam-cli/templates/expo-react-native/tailwind.config.js +10 -0
  257. package/codeyam-cli/templates/expo-react-native/tsconfig.json +10 -0
  258. package/codeyam-cli/templates/nextjs-prisma-sqlite/AUTH_PATTERNS.md +308 -0
  259. package/codeyam-cli/templates/nextjs-prisma-sqlite/AUTH_UPGRADE.md +304 -0
  260. package/codeyam-cli/templates/nextjs-prisma-sqlite/DATABASE.md +126 -0
  261. package/codeyam-cli/templates/nextjs-prisma-sqlite/FEATURE_PATTERNS.md +37 -0
  262. package/codeyam-cli/templates/nextjs-prisma-sqlite/README.md +53 -0
  263. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/codeyam-isolate/layout.tsx +12 -0
  264. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/lib/prisma.ts +9 -4
  265. package/codeyam-cli/templates/nextjs-prisma-sqlite/env +4 -0
  266. package/codeyam-cli/templates/nextjs-prisma-sqlite/gitignore +21 -0
  267. package/codeyam-cli/templates/nextjs-prisma-sqlite/package.json +5 -1
  268. package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma/seed.ts +4 -1
  269. package/codeyam-cli/templates/nextjs-prisma-sqlite/seed-adapter.ts +92 -0
  270. package/codeyam-cli/templates/nextjs-prisma-sqlite/vitest.config.ts +13 -0
  271. package/codeyam-cli/templates/nextjs-prisma-supabase/README.md +52 -0
  272. package/codeyam-cli/templates/{nextjs-prisma-sqlite/PRISMA_SETUP.md → nextjs-prisma-supabase/SUPABASE_SETUP.md} +37 -17
  273. package/codeyam-cli/templates/nextjs-prisma-supabase/app/api/todos/route.ts +17 -0
  274. package/codeyam-cli/templates/nextjs-prisma-supabase/app/globals.css +26 -0
  275. package/codeyam-cli/templates/nextjs-prisma-supabase/app/layout.tsx +34 -0
  276. package/codeyam-cli/templates/nextjs-prisma-supabase/app/lib/prisma.ts +20 -0
  277. package/codeyam-cli/templates/nextjs-prisma-supabase/app/lib/supabase.ts +12 -0
  278. package/codeyam-cli/templates/nextjs-prisma-supabase/app/page.tsx +10 -0
  279. package/codeyam-cli/templates/nextjs-prisma-supabase/env +9 -0
  280. package/codeyam-cli/templates/nextjs-prisma-supabase/eslint.config.mjs +11 -0
  281. package/codeyam-cli/templates/nextjs-prisma-supabase/gitignore +40 -0
  282. package/codeyam-cli/templates/nextjs-prisma-supabase/next.config.ts +11 -0
  283. package/codeyam-cli/templates/nextjs-prisma-supabase/package.json +37 -0
  284. package/codeyam-cli/templates/nextjs-prisma-supabase/postcss.config.mjs +7 -0
  285. package/codeyam-cli/templates/nextjs-prisma-supabase/prisma/schema.prisma +27 -0
  286. package/codeyam-cli/templates/nextjs-prisma-supabase/prisma/seed.ts +39 -0
  287. package/codeyam-cli/templates/nextjs-prisma-supabase/prisma.config.ts +12 -0
  288. package/codeyam-cli/templates/nextjs-prisma-supabase/tsconfig.json +34 -0
  289. package/codeyam-cli/templates/skills/codeyam-dev-mode/SKILL.md +2 -2
  290. package/codeyam-cli/templates/skills/codeyam-editor/SKILL.md +96 -17
  291. package/codeyam-cli/templates/skills/codeyam-memory/SKILL.md +10 -10
  292. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/detect-deprecated-patterns.mjs +139 -0
  293. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/find-exports.mjs +52 -0
  294. package/codeyam-cli/templates/skills/codeyam-memory/scripts/lib/read-json-field.mjs +61 -0
  295. package/codeyam-cli/templates/skills/codeyam-memory/scripts/lib/ripgrep-fallback.mjs +155 -0
  296. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/cleanup.mjs +13 -0
  297. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/filter-session.mjs +95 -0
  298. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/preprocess.mjs +160 -0
  299. package/package.json +14 -9
  300. package/packages/ai/src/lib/generateExecutionFlows.js +0 -11
  301. package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -1
  302. package/packages/analyze/src/lib/ProjectAnalyzer.js +10 -4
  303. package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
  304. package/packages/analyze/src/lib/asts/index.js +4 -2
  305. package/packages/analyze/src/lib/asts/index.js.map +1 -1
  306. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +0 -40
  307. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -1
  308. package/packages/database/src/lib/kysely/tables/editorScenariosTable.js +31 -0
  309. package/packages/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -1
  310. package/packages/database/src/lib/loadEntities.js +0 -6
  311. package/packages/database/src/lib/loadEntities.js.map +1 -1
  312. package/packages/database/src/lib/updateCommitMetadata.js +0 -25
  313. package/packages/database/src/lib/updateCommitMetadata.js.map +1 -1
  314. package/packages/types/src/enums/ProjectFramework.js +2 -0
  315. package/packages/types/src/enums/ProjectFramework.js.map +1 -1
  316. package/codeyam-cli/src/webserver/build/client/assets/Terminal-Dnj5CY9R.js +0 -41
  317. package/codeyam-cli/src/webserver/build/client/assets/addon-fit-CUXOrorO.js +0 -1
  318. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CMT1jU2q.js +0 -21
  319. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-BiM6z3Do.js +0 -1
  320. package/codeyam-cli/src/webserver/build/client/assets/editor-D1DAKXtT.js +0 -8
  321. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.dev-DkzqFzFj.js +0 -6
  322. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-C28BiQzt.js +0 -6
  323. package/codeyam-cli/src/webserver/build/client/assets/git-CFCTYk9I.js +0 -15
  324. package/codeyam-cli/src/webserver/build/client/assets/globals-B17TBSS6.css +0 -1
  325. package/codeyam-cli/src/webserver/build/client/assets/manifest-a632de18.js +0 -1
  326. package/codeyam-cli/src/webserver/build/client/assets/memory-Dg0mvYrI.js +0 -96
  327. package/codeyam-cli/src/webserver/build/client/assets/root-DUKqhFlb.js +0 -67
  328. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-ByhSyh0W.js +0 -1
  329. package/codeyam-cli/src/webserver/build/server/assets/index-HfLydfDq.js +0 -1
  330. package/codeyam-cli/src/webserver/build/server/assets/server-build-CUu_F-oo.js +0 -366
  331. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/detect-deprecated-patterns.sh +0 -108
  332. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/find-exports.sh +0 -69
  333. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/cleanup.sh +0 -12
  334. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/filter.jq +0 -45
  335. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/preprocess.sh +0 -139
@@ -4,10 +4,22 @@ import * as os from 'os';
4
4
  import { fileURLToPath } from 'url';
5
5
  import chalk from 'chalk';
6
6
  import { runAnalysisForEntities } from "../utils/analysisRunner.js";
7
- import { ProgressReporter } from "../utils/progress.js";
8
- import { initializeEnvironment } from "../utils/database.js";
9
- import { loadEntities, loadAnalyses } from "../../../packages/database/index.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
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 { ensureAnalyzerFinalized } from "../utils/analyzerFinalization.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 { scanScenarioFiles, syncScenarioFilesToDatabase, backfillScenarioMetadata, } from "../utils/scenariosManifest.js";
19
+ import { clearEditorState, clearEditorUserPrompt, validateStepTransition, } 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";
11
23
  const __filename = fileURLToPath(import.meta.url);
12
24
  const __dirname = path.dirname(__filename);
13
25
  const STEP_LABELS = {
@@ -23,6 +35,10 @@ const STEP_LABELS = {
23
35
  10: 'Verify',
24
36
  11: 'Journal',
25
37
  12: 'Review',
38
+ 13: 'Present',
39
+ 14: 'Commit',
40
+ 15: 'Finalize',
41
+ 16: 'Push',
26
42
  };
27
43
  /**
28
44
  * Append a JSONL log entry to .codeyam/logs/editor-log.jsonl
@@ -43,6 +59,18 @@ function logEvent(root, event, data) {
43
59
  // Logging is best-effort
44
60
  }
45
61
  }
62
+ /**
63
+ * Read the design system file if it exists.
64
+ */
65
+ function readDesignSystem(root) {
66
+ const designSystemPath = path.join(root, '.codeyam', 'design-system.md');
67
+ try {
68
+ return fs.readFileSync(designSystemPath, 'utf8');
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ }
46
74
  /**
47
75
  * Get the project root (where .codeyam/ lives) or cwd.
48
76
  */
@@ -79,15 +107,11 @@ function writeState(root, state) {
79
107
  }
80
108
  /**
81
109
  * Clear the editor state (for starting a new feature).
110
+ * Does NOT clear the user prompt file — that's handled separately
111
+ * via clearEditorUserPrompt when the previous feature commits.
82
112
  */
83
113
  function clearState(root) {
84
- const statePath = getStatePath(root);
85
- try {
86
- fs.unlinkSync(statePath);
87
- }
88
- catch {
89
- // File doesn't exist, that's fine
90
- }
114
+ clearEditorState(root);
91
115
  }
92
116
  /**
93
117
  * Check if a project has been scaffolded (package.json exists).
@@ -96,9 +120,27 @@ function hasProject(root) {
96
120
  return fs.existsSync(path.join(root, 'package.json'));
97
121
  }
98
122
  /**
99
- * Get the CodeYam server port from env or default.
123
+ * Get the CodeYam server port.
124
+ * Reads from the server state file first (actual running port), then falls
125
+ * back to CODEYAM_PORT env var, then to the default 3111.
126
+ * This is critical when the server auto-selected a different port because
127
+ * the default was occupied by another project's server.
100
128
  */
101
129
  function getServerPort() {
130
+ try {
131
+ const root = getProjectRoot();
132
+ if (root) {
133
+ const statePath = path.join(root, '.codeyam', 'server.json');
134
+ if (fs.existsSync(statePath)) {
135
+ const state = JSON.parse(fs.readFileSync(statePath, 'utf8'));
136
+ if (state.port)
137
+ return String(state.port);
138
+ }
139
+ }
140
+ }
141
+ catch {
142
+ // Fall through to defaults
143
+ }
102
144
  return process.env.CODEYAM_PORT || '3111';
103
145
  }
104
146
  /**
@@ -122,13 +164,13 @@ function stepHeader(step, title, feature) {
122
164
  console.log();
123
165
  }
124
166
  /**
125
- * Print a colored progress tracker showing all 11 steps.
167
+ * Print a colored progress tracker showing all 16 steps.
126
168
  * Steps before `current` are green ✓, `current` is bold cyan →, future steps are dim ○.
127
169
  */
128
170
  function printProgressTracker(current) {
129
171
  console.log();
130
- console.log(chalk.dim('┌─────────────────────────────────────┐'));
131
- for (let i = 1; i <= 12; i++) {
172
+ console.log(chalk.dim(' ┌─────────────────────────────────────┐'));
173
+ for (let i = 1; i <= 16; i++) {
132
174
  const label = STEP_LABELS[i];
133
175
  const num = i < 10 ? ` ${i}` : `${i}`;
134
176
  const content = `${num}. ${label.padEnd(28)}`;
@@ -166,7 +208,7 @@ function stopGate(current, opts) {
166
208
  console.log(chalk.yellow('For the CURRENT step (→), show each checklist item with ✓ (done) or ✗ (skipped + reason).'));
167
209
  console.log(chalk.yellow('If any items are ✗, explain why and ask if the user wants to address them.'));
168
210
  console.log();
169
- if (current < 12) {
211
+ if (current < 16) {
170
212
  console.log(chalk.green('When done, run: ') +
171
213
  chalk.bold(`codeyam editor ${current + 1}`));
172
214
  }
@@ -199,18 +241,25 @@ function printResumptionHeader(step) {
199
241
  'Check if glossary already populated:\n `cat .codeyam/glossary.json`',
200
242
  ],
201
243
  7: ['Check if isolation routes and registered scenarios already exist'],
202
- 8: [
203
- `Check existing scenarios:\n \`curl -s http://localhost:${port}/api/editor-scenarios\``,
204
- ],
244
+ 8: ['Check existing scenarios:\n `codeyam editor scenarios`'],
205
245
  9: [
206
- `Check existing user-persona scenarios:\n \`curl -s http://localhost:${port}/api/editor-scenarios\``,
246
+ 'Check existing user-persona scenarios:\n `codeyam editor scenarios`',
207
247
  ],
208
248
  10: ['Re-verify is safe to repeat — just re-run the checks'],
209
249
  11: [
210
- `Check if a journal entry already exists for this feature:\n \`curl -s http://localhost:${port}/api/editor-journal\``,
250
+ 'Check if a journal entry already exists for this feature:\n `codeyam editor journal-list`',
211
251
  'If an entry exists, use PATCH to update it — do NOT create a new one',
212
252
  ],
213
- 12: ['Check if commit already made:\n `git log --oneline -3`'],
253
+ 12: ['Re-verify is safe to repeat just re-run the checks'],
254
+ 13: ['Check if commit already made:\n `git log --oneline -3`'],
255
+ 14: ['Check if commit already made:\n `git log --oneline -3`'],
256
+ 15: [
257
+ 'Check if journal was already updated with commit SHA:\n `codeyam editor journal-list`',
258
+ 'Check if commit was already amended:\n `git log --oneline -3`',
259
+ ],
260
+ 16: [
261
+ 'Check if already pushed:\n `git remote -v && git log --oneline origin/HEAD..HEAD 2>/dev/null`',
262
+ ],
214
263
  };
215
264
  const label = STEP_LABELS[step] || 'Unknown';
216
265
  console.log(chalk.bold.yellow(`━━━ RESUMING Step ${step}: ${label} ━━━`));
@@ -315,7 +364,7 @@ function parseDebugTargets(target) {
315
364
  }
316
365
  if (entry.startsWith('step-')) {
317
366
  const num = parseInt(entry.replace('step-', ''), 10);
318
- if (!isNaN(num) && num >= 1 && num <= 12) {
367
+ if (!isNaN(num) && num >= 1 && num <= 16) {
319
368
  valid.add(`step-${num}`);
320
369
  continue;
321
370
  }
@@ -399,16 +448,87 @@ function printSetup(root) {
399
448
  console.log();
400
449
  console.log("No project detected. Let's get started.");
401
450
  console.log();
451
+ // ── Design System ────────────────────────────────────────────────
452
+ console.log(chalk.bold('Design System (ask FIRST):'));
453
+ console.log(chalk.dim(' Ask: "Do you have a design system, brand guidelines, or style preferences you\'d like me to follow?"'));
454
+ console.log(chalk.dim(' Use AskUserQuestion with these EXACT option labels:'));
455
+ console.log(chalk.yellow(' Option 1 label: "Yes, I\'ll paste my design system"'));
456
+ console.log(chalk.dim(' → Wait for paste, save to .codeyam/design-system.md, confirm with brief summary'));
457
+ console.log(chalk.yellow(' Option 2 label: "No, use sensible defaults"'));
458
+ console.log(chalk.dim(' → Skip'));
459
+ console.log();
402
460
  console.log(chalk.bold('Checklist:'));
403
461
  checkbox('Read `.codeyam/editor-mode-context.md` for session state');
404
462
  checkbox('Ask the user what they want to build');
405
463
  console.log();
464
+ // ── App Format Selection ───────────────────────────────────────────
465
+ console.log(chalk.bold('App Format Selection:'));
466
+ console.log(chalk.dim(' After the user describes their project, ask which app formats they want to target.'));
467
+ console.log(chalk.dim(' Use AskUserQuestion with CHECKBOXES (multiple selections allowed):'));
468
+ console.log();
469
+ for (const format of APP_FORMATS) {
470
+ console.log(chalk.yellow(` [ ] ${format.label}`) +
471
+ chalk.dim(` — ${format.description}`));
472
+ }
473
+ console.log();
474
+ // ── Tech Stack Selection ───────────────────────────────────────────
475
+ console.log(chalk.bold('Tech Stack Selection:'));
476
+ console.log(chalk.dim(' Based on the selected formats, present ONLY the matching tech stacks.'));
477
+ console.log(chalk.dim(' A stack matches if ANY of the user\'s selected formats appears in its "Supports" list.'));
478
+ console.log(chalk.dim(' Show ALL matching stacks even if there is only one. Mark the recommended option.'));
479
+ console.log(chalk.dim(' Use AskUserQuestion to let the user pick one.'));
480
+ console.log();
481
+ console.log(chalk.bold(' Available Tech Stacks:'));
482
+ for (const stack of TECH_STACKS) {
483
+ const recommended = stack.recommended ? chalk.green(' (Recommended)') : '';
484
+ const formatLabels = stack.supportedFormats
485
+ .map((f) => APP_FORMATS.find((af) => af.id === f)?.label)
486
+ .join(', ');
487
+ console.log(chalk.bold.yellow(` ${stack.name}`) +
488
+ recommended +
489
+ chalk.dim(` [id: ${stack.id}]`));
490
+ console.log(chalk.dim(` ${stack.description}`));
491
+ console.log(chalk.dim(' Technologies:'));
492
+ for (const tech of stack.technologies) {
493
+ console.log(chalk.dim(` - ${tech}`));
494
+ }
495
+ console.log(chalk.dim(` Supports: ${formatLabels}`));
496
+ console.log();
497
+ }
498
+ console.log(chalk.dim(' If NO stacks match the selected formats, tell the user that support for that format is coming soon'));
499
+ console.log(chalk.dim(' and suggest they pick a supported format for now.'));
500
+ console.log();
501
+ // ── Default Screen Size Selection ──────────────────────────────────
502
+ console.log(chalk.bold('Default Screen Size:'));
503
+ console.log(chalk.dim(' After selecting a tech stack, ask the user to choose the default screen size for previews and captures.'));
504
+ console.log(chalk.dim(' Use AskUserQuestion with RADIO buttons (single selection):'));
505
+ console.log();
506
+ console.log(chalk.yellow(' ( ) Desktop') + chalk.dim(' — 1440 × 900'));
507
+ console.log(chalk.yellow(' ( ) Laptop') + chalk.dim(' — 1024 × 768'));
508
+ console.log(chalk.yellow(' ( ) Tablet') + chalk.dim(' — 768 × 1024'));
509
+ console.log(chalk.yellow(' ( ) Mobile') + chalk.dim(' — 375 × 667'));
510
+ console.log(chalk.yellow(' ( ) Custom') + chalk.dim(' — ask for width × height'));
511
+ console.log();
512
+ 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).'));
513
+ console.log(chalk.dim(' If only one obvious choice, confirm it rather than asking.'));
514
+ 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}}\''));
515
+ console.log();
516
+ console.log(chalk.bold('Named Screen Sizes (for multi-resolution apps):'));
517
+ console.log(chalk.dim(' For mobile-responsive web apps or apps that need screenshots at multiple resolutions,'));
518
+ console.log(chalk.dim(' also save named screen sizes. Each scenario can reference a dimension name.'));
519
+ console.log(chalk.dim(' curl -s -X POST http://localhost:PORT/api/editor-project-info -H "Content-Type: application/json" \\'));
520
+ console.log(chalk.dim(' -d \'{"screenSizes":{"Desktop":{"width":1440,"height":900},"Mobile":{"width":375,"height":667}}}\''));
521
+ console.log();
406
522
  console.log(chalk.bold.red('━━━ STOP ━━━'));
407
523
  console.log();
408
- console.log(chalk.red('Ask the user what they want to build, then run:'));
524
+ 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:'));
409
525
  console.log();
410
- console.log(chalk.green(' ') + chalk.bold('codeyam editor 1 --feature "Feature Name"'));
526
+ console.log(chalk.green(' ') +
527
+ chalk.bold('codeyam editor 1 --feature "Feature Name" --app-formats "FORMAT_IDS" --tech-stack "STACK_ID" --prompt "the user\'s original message"'));
411
528
  console.log(chalk.dim(' Replace "Feature Name" with a short title for what the user described.'));
529
+ 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").'));
530
+ 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").'));
531
+ console.log(chalk.dim(" Pass --prompt with the user's exact original request so it appears in the journal."));
412
532
  console.log(chalk.dim(' Step 1 will guide you through planning and getting user confirmation before any code is written.'));
413
533
  console.log();
414
534
  }
@@ -426,9 +546,13 @@ function printCycleOverview(root, state) {
426
546
  console.log(chalk.dim('Or run ') +
427
547
  chalk.bold('codeyam editor 1') +
428
548
  chalk.dim(' to start a new feature'));
549
+ console.log();
550
+ console.log(chalk.yellow('If the user reports a bug or requests any change, run: ') +
551
+ chalk.bold('codeyam editor change'));
552
+ console.log(chalk.yellow('This applies even after committing — always use the change workflow.'));
429
553
  }
430
554
  else {
431
- console.log('Each feature follows 12 steps. You MUST run each command in order:');
555
+ console.log('Each feature follows 16 steps. You MUST run each command in order:');
432
556
  console.log();
433
557
  console.log(` ${chalk.bold.yellow(' 1')} ${chalk.bold('Plan')} — Plan the feature, confirm with user`);
434
558
  console.log(` ${chalk.bold.yellow(' 2')} ${chalk.bold('Prototype')} — Build a working prototype fast`);
@@ -441,29 +565,43 @@ function printCycleOverview(root, state) {
441
565
  console.log(` ${chalk.bold.yellow(' 9')} ${chalk.bold('User Scenarios')} — Create user-persona scenarios`);
442
566
  console.log(` ${chalk.bold.yellow('10')} ${chalk.bold('Verify')} — Review screenshots, check for errors`);
443
567
  console.log(` ${chalk.bold.yellow('11')} ${chalk.bold('Journal')} — Create/update journal entry`);
444
- console.log(` ${chalk.bold.yellow('12')} ${chalk.bold('Review')} — Present summary, get approval`);
568
+ console.log(` ${chalk.bold.yellow('12')} ${chalk.bold('Review')} — Verify screenshots and audit`);
569
+ console.log(` ${chalk.bold.yellow('13')} ${chalk.bold('Present')} — Present summary, get approval`);
570
+ console.log(` ${chalk.bold.yellow('14')} ${chalk.bold('Commit')} — Commit all changes`);
571
+ console.log(` ${chalk.bold.yellow('15')} ${chalk.bold('Finalize')} — Journal update + amend commit`);
572
+ console.log(` ${chalk.bold.yellow('16')} ${chalk.bold('Push')} — Push to remote`);
445
573
  console.log();
446
574
  console.log(chalk.green('Start now: ') + chalk.bold('codeyam editor 1'));
575
+ console.log(chalk.dim(' If the user already described what they want, pass it: codeyam editor 1 --prompt "their message"'));
447
576
  }
448
577
  console.log();
449
578
  }
450
579
  // ─── Step 1: Plan ─────────────────────────────────────────────────────
451
- function printStep1(root, feature) {
580
+ function printStep1(root, feature, options, userPrompt) {
581
+ const port = getServerPort();
452
582
  const prevState = readState(root);
453
583
  const isResuming = prevState?.step === 1;
454
584
  if (!isResuming) {
455
585
  clearState(root);
456
586
  }
457
- // If feature is provided, save initial state so step 2 can pick it up
458
- if (feature) {
459
- const now = new Date().toISOString();
460
- writeState(root, {
461
- feature,
462
- step: 1,
463
- label: STEP_LABELS[1],
464
- startedAt: isResuming ? prevState.startedAt : now,
465
- featureStartedAt: isResuming ? prevState.featureStartedAt : now,
466
- });
587
+ // Always persist state so step 2's validation sees that step 1 ran.
588
+ // The feature name may not be known yet (it's an output of planning)
589
+ // use an empty string as placeholder; step 2 requires --feature anyway.
590
+ const now = new Date().toISOString();
591
+ writeState(root, {
592
+ feature: feature || prevState?.feature || '',
593
+ step: 1,
594
+ label: STEP_LABELS[1],
595
+ startedAt: isResuming ? prevState.startedAt : now,
596
+ featureStartedAt: isResuming ? prevState.featureStartedAt : now,
597
+ appFormats: options?.appFormats || prevState?.appFormats,
598
+ techStackId: options?.techStackId || prevState?.techStackId,
599
+ });
600
+ // Save the user's original prompt to a separate file
601
+ if (userPrompt) {
602
+ const promptPath = path.join(root, '.codeyam', 'editor-user-prompt.txt');
603
+ fs.mkdirSync(path.dirname(promptPath), { recursive: true });
604
+ fs.writeFileSync(promptPath, userPrompt, 'utf8');
467
605
  }
468
606
  logEvent(root, 'step', { step: 1, label: 'Plan', feature });
469
607
  stepHeader(1, 'Plan', feature);
@@ -483,11 +621,24 @@ function printStep1(root, feature) {
483
621
  console.log(chalk.dim(' Bad: Free-form text asking "What do you think about the data model?"'));
484
622
  console.log(chalk.dim(' You can ask up to 4 questions at once. Bundle related questions into a single AskUserQuestion call.'));
485
623
  checkbox("Summarize what you'll build in plain language the user can verify against their vision");
486
- console.log();
487
- console.log(chalk.bold('Present a selection menu to the user (use AskUserQuestion):'));
488
- console.log(chalk.green(' "Looks good, start building!"') +
489
- chalk.dim(' proceed to step 2'));
490
- console.log(chalk.yellow(' "I\'d like some changes"') +
624
+ checkbox('Include a brief note on what interesting data states the scenarios should demonstrate');
625
+ console.log(chalk.dim(' Think: what seed data would put this feature through its paces? Diverse content, edge cases, empty vs rich.'));
626
+ checkbox('Set the project title and description for the App tab:');
627
+ console.log(chalk.dim(` curl -s -X POST http://localhost:${port}/api/editor-project-info \\`));
628
+ console.log(chalk.dim(' -H "Content-Type: application/json" \\'));
629
+ console.log(chalk.dim(' -d \'{"projectTitle":"My App","projectDescription":"A short description of what this app does"}\''));
630
+ console.log();
631
+ const designSystem = readDesignSystem(root);
632
+ if (designSystem) {
633
+ console.log(chalk.bold.magenta('Design System (from .codeyam/design-system.md):'));
634
+ console.log(chalk.dim(' Keep these design tokens in mind during planning.'));
635
+ console.log();
636
+ console.log(designSystem);
637
+ console.log();
638
+ }
639
+ console.log(chalk.bold('Present a selection menu to the user (use AskUserQuestion with these EXACT option labels):'));
640
+ console.log(chalk.green(' Option 1 label: "This plan is accurate, let\'s prototype it!"') + chalk.dim(' — proceed to step 2'));
641
+ console.log(chalk.yellow(' Option 2 label: "I\'d like some changes"') +
491
642
  chalk.dim(' — user describes changes, you revise the plan, then re-present'));
492
643
  console.log();
493
644
  console.log(chalk.dim('This step is for understanding user goals and getting buy-in. Code comes in Step 2.'));
@@ -522,6 +673,8 @@ function printStep2(root, feature) {
522
673
  label: STEP_LABELS[2],
523
674
  startedAt: isResuming ? prevState.startedAt : now,
524
675
  featureStartedAt: isResuming ? prevState.featureStartedAt : now,
676
+ appFormats: prevState?.appFormats,
677
+ techStackId: prevState?.techStackId,
525
678
  });
526
679
  logEvent(root, 'step', { step: 2, label: 'Prototype', feature });
527
680
  stepHeader(2, 'Prototype', feature);
@@ -532,68 +685,80 @@ function printStep2(root, feature) {
532
685
  console.log();
533
686
  // If no project exists yet, include scaffolding instructions first
534
687
  if (!projectExists) {
535
- const templateDir = path.join(__dirname, '..', '..', 'templates', 'nextjs-prisma-sqlite');
536
- const hasTemplate = fs.existsSync(templateDir);
537
688
  console.log(chalk.bold('Scaffold the project:'));
538
- if (hasTemplate) {
539
- checkbox('Copy the project template and install dependencies');
540
- console.log();
541
- console.log(chalk.dim(' Copy template (Next.js + Prisma 7 + SQLite, pre-configured):'));
542
- console.log(chalk.dim(` cp -r ${templateDir}/* .`));
543
- console.log(chalk.dim(` cp ${templateDir}/.env .`));
544
- console.log(chalk.dim(` cp ${templateDir}/gitignore .gitignore`));
545
- console.log(chalk.dim(' npm install'));
546
- console.log();
547
- checkbox('Define your data models in `prisma/schema.prisma`');
548
- console.log(chalk.dim(" Replace the placeholder Todo model with your app's models"));
549
- console.log();
550
- checkbox('Push schema and seed the database');
551
- console.log(chalk.dim(' npm run db:push'));
552
- console.log(chalk.dim(' # Edit prisma/seed.ts with your seed data, then:'));
553
- console.log(chalk.dim(' npm run db:seed'));
554
- console.log();
555
- console.log(chalk.dim(' See PRISMA_SETUP.md for Prisma patterns and important warnings.'));
556
- console.log(chalk.dim(' Key: import { prisma } from "@/app/lib/prisma" in API routes.'));
557
- console.log(chalk.dim(' Key: Seed scripts must use the adapter pattern (see prisma/seed.ts).'));
558
- }
559
- else {
560
- checkbox('Scaffold the project (Next.js App Router) using temp-dir-rsync pattern');
561
- console.log();
562
- console.log(chalk.dim(' Scaffolding pattern (avoids .claude/ conflicts):'));
563
- console.log(chalk.dim(' SCAFFOLD_DIR="/tmp/codeyam-scaffold-$$" && mkdir -p "$SCAFFOLD_DIR"'));
564
- console.log(chalk.dim(' npx create-next-app@latest "$SCAFFOLD_DIR" --typescript --tailwind --eslint \\'));
565
- console.log(chalk.dim(' --app --no-src-dir --no-import-alias --no-react-compiler --turbopack'));
566
- console.log(chalk.dim(' rsync -a --exclude=\'.git\' "$SCAFFOLD_DIR/" . && rm -rf "$SCAFFOLD_DIR"'));
567
- console.log();
568
- checkbox('Set up Prisma + SQLite database');
569
- console.log(chalk.dim(' npm install prisma @prisma/client @prisma/adapter-better-sqlite3 better-sqlite3'));
570
- console.log(chalk.dim(' npm install -D @types/better-sqlite3'));
571
- console.log(chalk.dim(' npx prisma init --datasource-provider sqlite'));
572
- console.log(chalk.dim(' # Define schema, then: npx prisma db push'));
573
- }
689
+ checkbox('Run `codeyam editor template` to scaffold, install dependencies, init git, and configure CodeYam');
690
+ console.log(chalk.dim(' This copies the Next.js + Prisma 7 + SQLite template, runs npm install,'));
691
+ console.log(chalk.dim(' initializes git, runs codeyam init, and refreshes the editor — all in one command.'));
574
692
  console.log();
575
- checkbox('Initialize git so analysis and commits work');
576
- console.log(chalk.dim(' git init && git add -A && git commit -m "Initial commit"'));
693
+ checkbox('Define your data models in `prisma/schema.prisma`');
694
+ console.log(chalk.dim(" Replace the placeholder Todo model with your app's models"));
577
695
  console.log();
578
- checkbox('Run `codeyam init --force --keep-server` to detect the project and configure it');
579
- console.log(chalk.dim(' This auto-detects webapps and configures the start command for analysis'));
696
+ checkbox('Push schema and seed the database');
697
+ console.log(chalk.dim(' npm run db:push'));
698
+ console.log(chalk.dim(' # Edit prisma/seed.ts with your seed data, then:'));
699
+ console.log(chalk.dim(' npm run db:seed'));
700
+ console.log(chalk.dim(` # After re-seeding, restart the dev server to pick up fresh data:`));
701
+ console.log(chalk.dim(` # codeyam editor dev-server '{"action":"restart"}'`));
580
702
  console.log();
581
- checkbox('Verify `.codeyam/config.json` has `startCommand` in the webapp entry');
582
- console.log(chalk.dim(' Should look like: "startCommand": { "command": "sh", "args": ["-c", "npm run dev -- --port $PORT"] }'));
583
- console.log(chalk.dim(' If missing, add it manually. $PORT is replaced at runtime by the analyzer.'));
703
+ console.log(chalk.yellow(' IMPORTANT: When adding new required columns to existing tables,'));
704
+ console.log(chalk.yellow(' provide a @default(...) value so `db push` can fill existing rows.'));
705
+ console.log(chalk.dim(' Example: userId String @default("anonymous") — existing rows get "anonymous"'));
706
+ console.log(chalk.dim(' Without a default, Prisma requires --force-reset which drops ALL data.'));
707
+ console.log(chalk.dim(' NEVER use --force-reset — it is blocked in this environment.'));
584
708
  console.log();
585
- checkbox(`Notify CodeYam: \`curl -s -X POST http://localhost:${port}/api/editor-refresh\``);
709
+ console.log(chalk.dim(' See DATABASE.md for Prisma patterns and important warnings.'));
710
+ console.log(chalk.dim(' Key: import { prisma } from "@/app/lib/prisma" in API routes.'));
711
+ console.log(chalk.dim(' Key: Seed scripts must use the adapter pattern (see prisma/seed.ts).'));
586
712
  console.log();
587
713
  console.log(chalk.bold('Build the feature:'));
588
714
  }
589
715
  console.log(chalk.bold('Checklist:'));
590
- checkbox('Create/update API routes (real database reads via Prisma)');
716
+ checkbox('Create API routes that read from the database via Prisma');
591
717
  checkbox('Seed the database with demo data');
592
- checkbox('Build the page/feature UI components');
718
+ checkbox('Create `.codeyam/seed-adapter.ts` so CodeYam can seed the database for scenarios');
719
+ console.log(chalk.dim(' The seed adapter reads a JSON file (path passed as CLI arg), wipes tables, inserts rows.'));
720
+ console.log(chalk.dim(" Use the project's own ORM (Prisma, Drizzle, etc.). See template for example."));
721
+ console.log(chalk.dim(' Run with: npx tsx .codeyam/seed-adapter.ts <path-to-seed-data.json>'));
593
722
  checkbox('Verify the dev server shows the changes');
723
+ checkbox('If the feature involves auth, email, payments, or other common patterns: read FEATURE_PATTERNS.md');
724
+ // Responsive design guidance when building a mobile-responsive web app
725
+ if (prevState?.appFormats?.includes('mobile-responsive-web-app')) {
726
+ console.log();
727
+ console.log(chalk.bold.magenta('Responsive Design (mobile-responsive-web-app):'));
728
+ console.log(chalk.magenta(' This app must look great on BOTH desktop AND mobile. It is NOT a mobile-only app.'));
729
+ console.log(chalk.magenta(' Design desktop-first with a full-width layout, then ensure it adapts gracefully to mobile.'));
730
+ console.log(chalk.dim(' Use Tailwind responsive prefixes (sm:, md:, lg:) for layout shifts.'));
731
+ console.log(chalk.dim(' Test at both Desktop (1280×800) and Mobile (390×844) sizes before presenting.'));
732
+ }
733
+ const designSystem = readDesignSystem(root);
734
+ if (designSystem) {
735
+ console.log();
736
+ console.log(chalk.bold.magenta('Design System (from .codeyam/design-system.md):'));
737
+ console.log();
738
+ console.log(designSystem);
739
+ console.log();
740
+ checkbox('Define ALL design tokens as CSS custom properties in globals.css — not just colors');
741
+ console.log(chalk.dim(' Colors: --bg-surface, --text-primary, --accent-green-a, etc.'));
742
+ console.log(chalk.dim(' Typography: --text-xs, --text-sm, --text-lg, --text-2xl (font-size values)'));
743
+ console.log(chalk.dim(' Font weights: --font-weight-normal, --font-weight-medium, --font-weight-semibold'));
744
+ console.log(chalk.dim(' Spacing: --spacing-xs, --spacing-sm, --spacing-md, --spacing-lg, etc.'));
745
+ console.log(chalk.dim(' Border radius, shadows, transitions — every value the design system defines.'));
746
+ checkbox('Reference tokens from components — ZERO hardcoded px values for font-size, spacing, or colors');
747
+ console.log(chalk.dim(' Bad: fontSize: 14, padding: "12px 16px", gap: 8'));
748
+ console.log(chalk.dim(' Good: fontSize: "var(--text-sm)", padding: "var(--spacing-md) var(--spacing-lg)", gap: "var(--spacing-sm)"'));
749
+ console.log(chalk.dim(' This ensures the entire app updates when the design system changes.'));
750
+ }
751
+ console.log();
752
+ console.log(chalk.bold.cyan('Keep the preview moving:'));
753
+ console.log(chalk.cyan(' The user is watching the preview. Refresh it after each meaningful change:'));
754
+ console.log(chalk.cyan(` codeyam editor preview`));
755
+ console.log(chalk.cyan(' Refresh after: first visible page, adding each UI section, seeding data, styling.'));
756
+ console.log(chalk.cyan(' Aim for 4-8+ refreshes during prototyping — not one big reveal at the end.'));
757
+ console.log(chalk.cyan(' If you build a NEW page (e.g., /drinks/[id]), navigate the preview there:'));
758
+ console.log(chalk.cyan(` codeyam editor preview '{"path":"/drinks/1"}'`));
594
759
  console.log();
595
760
  console.log(chalk.bold('Verify the dev server:'));
596
- console.log(chalk.dim(` # Get dev server URL: curl -s http://localhost:${port}/api/editor-dev-server`));
761
+ console.log(chalk.dim(` # Get dev server URL: codeyam editor dev-server`));
597
762
  console.log(chalk.dim(' # Check page loads: curl -s -o /dev/null -w "%{http_code}" http://localhost:<dev-port>'));
598
763
  console.log(chalk.dim(' # Check API routes: curl -s http://localhost:<dev-port>/api/your-route'));
599
764
  console.log();
@@ -601,10 +766,22 @@ function printStep2(root, feature) {
601
766
  console.log(chalk.yellow(' Verify everything works before presenting the prototype to the user.'));
602
767
  checkbox('Verify the page loads: curl the dev server URL and confirm HTTP 200 (not an error page)');
603
768
  checkbox('Verify API routes return valid JSON: curl each route and confirm no error responses');
604
- checkbox('Check for broken images: look at any <img> src attributes and verify the assets exist');
769
+ checkbox('Check for broken images: `codeyam editor verify-images \'{"paths":["/"], "imageUrls":["url1","url2"]}\'`');
770
+ console.log(chalk.dim(' Pass ALL page paths and ALL image URLs you used in seed data / API responses.'));
771
+ console.log(chalk.dim(' Client-rendered pages need imageUrls — the HTML shell has no images to scan.'));
772
+ console.log(chalk.dim(' Fix or replace any broken image URLs in the seed data before proceeding.'));
605
773
  checkbox('Check the dev server terminal output for runtime errors (missing modules, failed imports)');
774
+ checkbox('Verify the live preview renders: `codeyam editor client-errors`');
775
+ console.log(chalk.dim(' If `hasContent=false` or `liveErrors>0`, the preview is broken — fix the issue before proceeding.'));
776
+ console.log(chalk.dim(' The user is looking at the preview — a blank page means something is broken.'));
606
777
  console.log(chalk.dim(' If any check fails, fix the issue and re-verify before proceeding.'));
607
778
  console.log();
779
+ console.log(chalk.bold('Update README and setup script:'));
780
+ checkbox('Update `README.md`: set the project name, write a one-line description, and list any setup prerequisites');
781
+ checkbox('Update `npm run setup` in `package.json` if setup requires extra steps (e.g. env vars, external services)');
782
+ console.log(chalk.dim(' The README and setup script must stay accurate as you make changes.'));
783
+ console.log(chalk.dim(' A new clone should work with just: git clone → npm run setup → npm run dev'));
784
+ console.log();
608
785
  console.log(chalk.dim('Focus on building the prototype. Scenarios and refactoring happen in later steps.'));
609
786
  stopGate(2);
610
787
  }
@@ -629,29 +806,33 @@ function printStep3(root, feature) {
629
806
  console.log('Summarize what was built and get user confirmation.');
630
807
  console.log();
631
808
  console.log(chalk.bold('Before presenting — verify everything works:'));
632
- checkbox(`Refresh the preview: \`curl -s -X POST http://localhost:${port}/api/editor-refresh\``);
633
- checkbox(`Refresh and check for SSR errors: \`curl -s -X POST http://localhost:${port}/api/dev-mode-preview\` — look at the \`preview\` field for \`healthy: false\``);
809
+ checkbox(`Refresh the preview: \`codeyam editor preview\` check the \`preview\` field for \`healthy: false\``);
634
810
  checkbox('Verify API routes return valid data (curl each route)');
635
- checkbox(`Navigate to each page and check health: \`curl -s -X POST http://localhost:${port}/api/dev-mode-preview -H 'Content-Type: application/json' -d '{"path":"/your-route"}'\``);
636
811
  console.log();
637
- console.log(chalk.bold(' Check for broken images on each page:'));
638
- checkbox('Get the dev server URL from `curl -s http://localhost:' +
639
- port +
640
- '/api/editor-dev-server` (the `url` field)');
641
- checkbox('For each page: `curl -s <dev-server-url>/your-route` and inspect `<img>` src attributes');
642
- checkbox('Verify every image src is a valid path (not a missing file, placeholder URL, or broken reference)');
643
- checkbox('If any images are broken: fix the src (use real assets, placeholders from a CDN, or remove the image)');
644
- console.log(chalk.yellow(' Do not present to the user until all checks pass. Fix issues first.'));
812
+ console.log(chalk.bold.red(' Verify EVERY image loads (this is the #1 source of broken prototypes):'));
813
+ checkbox('Run `codeyam editor verify-images \'{"paths":["/"], "imageUrls":["url1","url2"]}\'`');
814
+ console.log(chalk.dim(' Include ALL page paths and ALL image URLs from seed data / API responses.'));
815
+ console.log(chalk.dim(' Client-rendered pages need imageUrls — the HTML shell has no images.'));
816
+ checkbox('Fix or remove any image that returns non-200 before continuing');
817
+ checkbox('Check for client-side errors: `codeyam editor client-errors`');
818
+ console.log(chalk.dim(' If there are errors, fix the underlying issue before presenting.'));
819
+ checkbox('Verify `hasContent=true` and `liveErrors=0` — do NOT ask the user to confirm if the preview is broken');
645
820
  console.log();
646
821
  console.log(chalk.bold('Then present to the user:'));
647
822
  checkbox('Summarize what was built (routes, components, data)');
648
- checkbox('Show the user the current state of the prototype');
823
+ checkbox('Navigate the preview to the feature\'s primary page: `codeyam editor preview \'{"path":"/your-page"}\'`');
824
+ console.log(chalk.dim(' The user needs to SEE the new feature. If you built a new page, navigate there.'));
825
+ console.log(chalk.dim(' If you modified an existing page, refresh the preview to show the changes.'));
649
826
  console.log();
650
- console.log(chalk.bold('Present a selection menu to the user (use AskUserQuestion):'));
651
- console.log(chalk.green(' "Yes, this looks right!"') +
652
- chalk.dim(' proceed to step 4'));
653
- console.log(chalk.yellow(' "I\'d like some changes"') +
654
- chalk.dim(' — user describes changes, you make them, then re-present'));
827
+ console.log(chalk.bold.cyan('Guide the user through interactive testing:'));
828
+ checkbox('Tell the user: "The preview is fully interactive — click around to test!"');
829
+ checkbox('Prompt the user to try key interactions: forms, navigation, buttons, etc.');
830
+ checkbox('Ask the user: "Does everything work as expected?"');
831
+ console.log();
832
+ console.log(chalk.bold('Present a selection menu to the user (use AskUserQuestion with these EXACT option labels):'));
833
+ console.log(chalk.green(' Option 1 label: "The live preview is displaying what I expected"') + chalk.dim(' — proceed to step 4'));
834
+ console.log(chalk.yellow(' Option 2 label: "I\'d like some changes"') +
835
+ chalk.dim(' — make changes, refresh preview, re-run `codeyam editor 3`'));
655
836
  console.log();
656
837
  console.log(chalk.dim('Wait for user approval before moving on. Refactoring and scenarios happen in later steps.'));
657
838
  stopGate(3, { confirm: true });
@@ -708,6 +889,7 @@ function printStep4(root, feature) {
708
889
  }
709
890
  // ─── Step 5: Extract ──────────────────────────────────────────────────
710
891
  function printStep5(root, feature) {
892
+ const port = getServerPort();
711
893
  const prevState = readState(root);
712
894
  const isResuming = prevState?.step === 5;
713
895
  const now = new Date().toISOString();
@@ -731,12 +913,13 @@ function printStep5(root, feature) {
731
913
  checkbox('Every component that renders multiple sections must be split into sub-components');
732
914
  console.log(chalk.dim(' No tests needed — visual verification happens in step 7'));
733
915
  console.log();
734
- console.log(chalk.bold('Library functions (TDD):'));
735
- checkbox('For each function: write MULTIPLE failing tests FIRST, then extract to make them pass');
916
+ console.log(chalk.bold('Library functions AND hooks (TDD):'));
917
+ checkbox('For each function/hook: write MULTIPLE failing tests FIRST, then extract to make them pass');
736
918
  console.log(chalk.dim(' Cover: typical inputs, edge cases, empty/null inputs, error conditions'));
737
919
  console.log(chalk.dim(' Aim for 3-8 test cases per function depending on complexity'));
920
+ console.log(chalk.dim(' Hooks count as functions — useDrinks, useAuth, etc. all need test files'));
738
921
  checkbox('Place test files next to source: `app/lib/drinks.ts` → `app/lib/drinks.test.ts`');
739
- console.log(chalk.yellow(' Tests ARE the only coverage for library functions — step 7 only captures component screenshots.'));
922
+ console.log(chalk.yellow(' Tests ARE the only coverage for library functions/hooks — step 7 only captures component screenshots.'));
740
923
  console.log();
741
924
  console.log(chalk.bold('Recursive pass:'));
742
925
  checkbox('Re-read EVERY new file you just created — extract components from components, functions from functions');
@@ -748,6 +931,8 @@ function printStep5(root, feature) {
748
931
  checkbox('Run all tests and verify they pass');
749
932
  checkbox('Page files contain ONLY imports + component composition — no raw HTML tags');
750
933
  checkbox('Every component renders ONE thing or composes sub-components — no multi-section JSX');
934
+ checkbox(`Refresh the preview after each batch of extractions: \`codeyam editor preview\``);
935
+ console.log(chalk.dim(' The user should see the preview stay healthy as you refactor — refresh periodically, not just at the end.'));
751
936
  console.log(chalk.dim('Reuse glossary functions when they fit naturally. Extract a new function when the use case diverges.'));
752
937
  console.log();
753
938
  console.log(chalk.dim('Focus on TDD for functions and extraction for components. Scenarios come in later steps.'));
@@ -776,7 +961,8 @@ function printStep6(root, feature) {
776
961
  checkbox("Read `.codeyam/glossary.json` (create if it doesn't exist)");
777
962
  checkbox('Add an entry for each new function/component extracted in step 5');
778
963
  checkbox('Each entry should have: name, filePath, description, parameters, returnType, tags, feature');
779
- checkbox('For each function with a test file from step 5, set `testFile` to the relative path');
964
+ checkbox('Every non-component entry MUST have `testFile` set hooks and functions all need tests');
965
+ console.log(chalk.yellow(' If a function/hook has no test yet, go back and write one (TDD). The audit will block you.'));
780
966
  console.log();
781
967
  console.log(chalk.bold('Entry format:'));
782
968
  console.log(chalk.dim(' { "name": "calculateTotal", "filePath": "app/utils/pricing.ts",'));
@@ -811,7 +997,13 @@ function printStep7(root, feature) {
811
997
  console.log();
812
998
  console.log(chalk.bold('Visual Components — Component Isolation:'));
813
999
  checkbox('List all files with new/modified visual components from step 5');
814
- checkbox('Ensure `.gitignore` includes `**/codeyam-isolate*` (add if missing)');
1000
+ checkbox('Create isolation route dirs: `codeyam editor isolate "ComponentA ComponentB ..."`');
1001
+ console.log(chalk.dim(' This creates app/isolated-components/layout.tsx (with production notFound() guard) and'));
1002
+ console.log(chalk.dim(' a directory per component. List ALL components that need isolation routes.'));
1003
+ checkbox('Check existing scenarios: `codeyam editor scenarios`');
1004
+ console.log(chalk.dim(' Reuse and improve existing scenarios where possible — update mock data'));
1005
+ console.log(chalk.dim(' to reflect current changes. Add new scenarios only for genuinely new states.'));
1006
+ console.log(chalk.dim(' Ensure at least one scenario clearly demonstrates what changed in this session.'));
815
1007
  checkbox('For each visual component:');
816
1008
  console.log(chalk.dim(' 1. Read the source AND find where it is used in the app to understand:'));
817
1009
  console.log(chalk.dim(' — Props/interface'));
@@ -822,8 +1014,8 @@ function printStep7(root, feature) {
822
1014
  console.log(chalk.dim(' — Different visual states: loading, error, disabled, selected, hover'));
823
1015
  console.log(chalk.dim(' — Boundary values: single item vs many, min/max ratings, very long names'));
824
1016
  console.log(chalk.dim(' 3. Create ONE isolation route per component with a scenarios map and ?s= query param:'));
825
- console.log(chalk.dim(' Remix: app/routes/codeyam-isolate.ComponentName.tsx → /codeyam-isolate/ComponentName'));
826
- console.log(chalk.dim(' Next.js: app/codeyam-isolate/ComponentName/page.tsx → /codeyam-isolate/ComponentName'));
1017
+ console.log(chalk.dim(' Remix: app/routes/isolated-components.ComponentName.tsx → /isolated-components/ComponentName'));
1018
+ console.log(chalk.dim(' Next.js: app/isolated-components/ComponentName/page.tsx → /isolated-components/ComponentName'));
827
1019
  console.log(chalk.dim(' The route defines a `scenarios` object mapping scenario names to props,'));
828
1020
  console.log(chalk.dim(' reads `?s=ScenarioName` from the URL, and renders the component with those props.'));
829
1021
  console.log(chalk.dim(' Wrap the component in a capture container with id="codeyam-capture":'));
@@ -836,15 +1028,19 @@ function printStep7(root, feature) {
836
1028
  console.log(chalk.dim(' 4. Wait 2 seconds for HMR, then register + capture each scenario:'));
837
1029
  console.log(chalk.dim(` codeyam editor register '{"name":"ComponentName - Scenario",`));
838
1030
  console.log(chalk.dim(` "componentName":"ComponentName","componentPath":"path/to/file.tsx",`));
839
- console.log(chalk.dim(` "url":"/codeyam-isolate/ComponentName?s=Scenario",`));
1031
+ console.log(chalk.dim(` "url":"/isolated-components/ComponentName?s=Scenario",`));
840
1032
  console.log(chalk.dim(` "mockData":{"routes":{"/api/...":{"body":[...]}}}}'`));
1033
+ console.log(chalk.dim(' Optional: add "dimension" to use a named screen size, or "viewportWidth"/"viewportHeight" for raw override'));
1034
+ console.log(chalk.dim(' If omitted, captures use the project default from setup. Only override for scenarios that need a different size.'));
841
1035
  console.log(chalk.dim(' url is a PATH (starts with /) — the proxy routes it and intercepts API calls'));
842
1036
  console.log(chalk.dim(' mockData.routes provides data for API calls the component makes internally'));
843
1037
  console.log(chalk.dim(' (omit mockData if the component has no internal API calls)'));
1038
+ console.log(chalk.dim(' For large JSON: use your Write tool to create .codeyam/tmp/scenario.json,'));
1039
+ console.log(chalk.dim(' then: codeyam editor register @.codeyam/tmp/scenario.json'));
844
1040
  console.log(chalk.yellow(' 5. IMPORTANT: Check the register response for `clientErrors` array'));
845
1041
  console.log(chalk.yellow(' If clientErrors is non-empty → fix the isolation route and re-register'));
846
1042
  console.log(chalk.yellow(' Fix client errors and re-register before moving on'));
847
- console.log(chalk.dim(' Isolation routes stay in the project (in .gitignore) so the editor preview can display them'));
1043
+ console.log(chalk.dim(' Isolation routes are committed to git the layout guard blocks them in production'));
848
1044
  console.log();
849
1045
  console.log(chalk.bold('Library Functions — run tests:'));
850
1046
  checkbox('Run ALL test files created in step 5');
@@ -854,7 +1050,10 @@ function printStep7(root, feature) {
854
1050
  console.log();
855
1051
  console.log(chalk.dim('Do not proceed until both component isolations and library tests pass.'));
856
1052
  console.log();
857
- checkbox('Run `codeyam editor audit` to verify all components have scenarios and all functions have tests');
1053
+ checkbox('Run `codeyam editor audit` to verify all components have scenarios and all functions/hooks have tests');
1054
+ console.log(chalk.red.bold(' The audit is a HARD GATE — step 8 will refuse to run until the audit passes.'));
1055
+ console.log(chalk.dim(' When audit passes, the import graph is built automatically for change tracking.'));
1056
+ console.log();
858
1057
  stopGate(7);
859
1058
  }
860
1059
  // ─── Step 8: App Scenarios ────────────────────────────────────────────
@@ -875,19 +1074,75 @@ function printStep8(root, feature) {
875
1074
  if (isResuming) {
876
1075
  printResumptionHeader(8);
877
1076
  }
878
- console.log('Create app-level scenarios representing different data states.');
1077
+ console.log('Create app-level scenarios with rich data that robustly demonstrates this feature.');
1078
+ console.log();
1079
+ console.log(chalk.bold('Goal: Every scenario should thoroughly exercise the feature with realistic data.'));
1080
+ console.log(chalk.dim(' Scenarios with minimal or generic data ("Test Item 1") won\'t reveal whether the feature works.'));
1081
+ console.log(chalk.dim(' Use rich, diverse seed data that puts the feature through its paces.'));
1082
+ console.log();
1083
+ console.log(chalk.bold.cyan('Make seed data work hard:'));
1084
+ console.log(chalk.cyan(' Every scenario — new or existing — should have data that EXERCISES the feature:'));
1085
+ console.log(chalk.cyan(' • Add data that uses new fields, relationships, or states the feature introduces'));
1086
+ console.log(chalk.cyan(' • Include realistic variety — different categories, lengths, statuses, counts'));
1087
+ console.log(chalk.cyan(" • Populate optional fields the feature depends on (don't leave them empty)"));
1088
+ console.log(chalk.cyan(' • Make content diverse enough that edge cases surface naturally'));
1089
+ console.log(chalk.cyan(" • Think: would this data reveal a bug in the feature? If it's too simple, enrich it."));
1090
+ console.log();
1091
+ console.log(chalk.bold.cyan('When to create new vs reuse existing:'));
1092
+ console.log(chalk.cyan(' • New pages or pages with no scenarios yet → create new scenarios'));
1093
+ console.log(chalk.cyan(' • Existing scenarios on affected pages → re-register with enhanced data'));
1094
+ console.log(chalk.cyan(" • New data states that can't coexist in one scenario (empty vs rich, error vs success) → new scenario"));
1095
+ console.log(chalk.cyan(" • Don't duplicate — if an existing scenario can cover a state with richer data, enhance it instead"));
879
1096
  console.log();
880
1097
  console.log(chalk.bold('Checklist:'));
881
- checkbox('Create scenarios for key data states (empty, loaded, error)');
882
- console.log(chalk.dim(' Each scenario provides data across ALL API routes for that state'));
883
- console.log(chalk.dim(' Name app scenarios with "App - " prefix: "App - Empty", "App - Full Catalog", "App - API Error"'));
884
- checkbox('Register each scenario (auto-captures screenshot):');
885
- console.log(chalk.dim(` codeyam editor register '{"name":"App - Empty","description":"...","mockData":{"routes":{"/api/...":{"body":[...]}}}}'`));
1098
+ checkbox('Run `codeyam editor scenarios` review all existing scenarios');
1099
+ checkbox("Create new scenarios for any pages that don't have scenarios yet");
1100
+ console.log(chalk.yellow(' Each page needs its own scenarios a detail page needs different data than the catalog'));
1101
+ checkbox('Re-register every existing scenario whose page was affected by this feature');
1102
+ console.log(chalk.dim(' Use the SAME name to update. Enhance seed data to showcase this feature where relevant.'));
1103
+ console.log(chalk.yellow(" Don't just re-register unchanged data — enrich it so the feature is thoroughly demonstrated."));
1104
+ checkbox('If the project has a database + seed adapter, use seed-based scenarios:');
1105
+ console.log(chalk.dim(` codeyam editor register '{"name":"Full Catalog","type":"application","url":"/","seed":{"products":[...],"categories":[...]}}'`));
1106
+ console.log(chalk.dim(' Seed data is written to the DB via the seed adapter. Real app renders real data.'));
1107
+ checkbox('Optional: add "dimension" to use a named screen size (e.g. "Mobile", "Desktop")');
1108
+ console.log(chalk.dim(' References a named size from config screenSizes. For multi-resolution: register "Home - Desktop" with dimension "Desktop"'));
1109
+ console.log(chalk.dim(' and "Home - Mobile" with dimension "Mobile". Or use raw "viewportWidth"/"viewportHeight" to override directly.'));
1110
+ checkbox('IMPORTANT: Always include "url" — the page path to screenshot for this scenario');
1111
+ console.log(chalk.dim(' Use "/" for home page, "/drinks/1" for detail pages, etc.'));
1112
+ console.log(chalk.dim(' Without url, the screenshot captures the root page regardless of the scenario.'));
1113
+ console.log(chalk.yellow(' Create separate scenarios for each page that shows different data.'));
1114
+ checkbox('For large seed data, use your Write tool to create .codeyam/tmp/scenario.json, then:');
1115
+ console.log(chalk.dim(' codeyam editor register @.codeyam/tmp/scenario.json'));
1116
+ console.log(chalk.yellow(' IMPORTANT: Use the Write tool — NOT cat/heredoc — to avoid permission prompts'));
1117
+ checkbox('For external API mocks (Stripe, weather, etc.), add externalApis:');
1118
+ console.log(chalk.dim(` "externalApis":{"GET https://api.stripe.com/v1/prices":{"body":[...],"status":200}}`));
1119
+ checkbox('If the app uses auth, email, or other patterns: see FEATURE_PATTERNS.md for scenario guidance');
1120
+ checkbox('If the app uses localStorage/sessionStorage instead of a database, use localStorage scenarios:');
1121
+ console.log(chalk.dim(` codeyam editor register '{"name":"Full Library","type":"application","url":"/","localStorage":{"articles":[...],"collections":[...]}}'`));
1122
+ console.log(chalk.dim(' The proxy injects data into localStorage before the app loads. Fully interactive — the app can read and write normally.'));
1123
+ console.log(chalk.dim(' For an empty state, register with an empty localStorage or omit it entirely.'));
1124
+ checkbox('If no database and no localStorage, use component-style mock scenarios:');
1125
+ console.log(chalk.dim(` codeyam editor register '{"name":"Empty","description":"...","url":"/","mockData":{"routes":{"/api/...":{"body":[...]}}}}'`));
886
1126
  checkbox('After each registration, check the response for `clientErrors`');
887
1127
  console.log(chalk.yellow(' If clientErrors is non-empty → fix the issue and re-register the scenario'));
888
1128
  console.log(chalk.yellow(' Fix client errors and re-register before moving on'));
1129
+ checkbox('CRITICAL: After EACH registration, view the captured screenshot to verify it');
1130
+ console.log(chalk.yellow(' Read the screenshot file path from the registration response and view it.'));
1131
+ console.log(chalk.yellow(' Does the screenshot actually SHOW the data you put in? If you seeded 5 articles'));
1132
+ console.log(chalk.yellow(' but the screenshot shows an empty page, the scenario is broken — fix the code or data.'));
1133
+ console.log(chalk.yellow(' Do NOT create scenarios with data the app cannot yet render.'));
889
1134
  console.log();
890
1135
  console.log(chalk.dim('Focus on creating and registering app-level scenarios. Code fixes happen in step 10 if needed.'));
1136
+ console.log();
1137
+ console.log(chalk.bold.cyan("Verify your work — screenshots don't lie:"));
1138
+ console.log(chalk.cyan(' • View every captured screenshot. Does it show what the scenario name promises?'));
1139
+ console.log(chalk.cyan(' • A "Library with Articles" screenshot showing an empty page means the scenario is BROKEN.'));
1140
+ console.log(chalk.cyan(' • Is the seed data diverse — different lengths, categories, counts — or just placeholders?'));
1141
+ console.log(chalk.cyan(' • Only create scenarios for states the CURRENT code can render.'));
1142
+ console.log();
1143
+ console.log(chalk.bold.yellow('GATE: Before proceeding, run `codeyam editor scenario-coverage`'));
1144
+ console.log(chalk.yellow(' This checks which existing scenarios have stale screenshots.'));
1145
+ console.log(chalk.yellow(' Re-register every stale scenario listed until the check passes.'));
891
1146
  stopGate(8);
892
1147
  }
893
1148
  // ─── Step 9: User Scenarios ───────────────────────────────────────────
@@ -908,21 +1163,29 @@ function printStep9(root, feature) {
908
1163
  if (isResuming) {
909
1164
  printResumptionHeader(9);
910
1165
  }
911
- console.log('Create per-persona scenarios if the app has users. Skip to step 10 if no users.');
1166
+ console.log('Create per-persona variations of existing scenarios. Skip to step 10 if no users.');
1167
+ console.log();
1168
+ console.log(chalk.bold('If the app has NO users/auth:'));
1169
+ console.log(chalk.dim(' Skip this step and proceed to step 10 (Verify).'));
1170
+ console.log();
1171
+ console.log(chalk.bold('If the app has users/auth:'));
912
1172
  console.log();
913
- console.log(chalk.bold('If the app has users:'));
914
- checkbox('Create scenarios for each user persona (admin, regular user, new user)');
915
- console.log(chalk.dim(' Each persona scenario provides data across ALL API routes for that user type'));
916
- checkbox('Register each persona scenario (auto-captures screenshot):');
917
- console.log(chalk.dim(` codeyam editor register '{"name":"...","description":"...","mockData":{"routes":{"/api/...":{"body":[...]}}}}'`));
1173
+ console.log(chalk.bold('Goal: Create persona variations of EXISTING app scenarios.'));
1174
+ console.log(chalk.dim(' Do NOT create standalone persona scenarios. Each user-persona scenario should be'));
1175
+ console.log(chalk.dim(' a variation of an existing app scenario from step 8, with user-specific state layered on.'));
1176
+ console.log();
1177
+ console.log(chalk.bold('Checklist:'));
1178
+ checkbox('Run `codeyam editor scenarios` — list all existing app scenarios');
1179
+ checkbox('For EACH existing app scenario, create a logged-in variation:');
1180
+ console.log(chalk.dim(' Copy the scenario seed data and add "session":{"cookieValue":"sess_alice"} + user seed'));
1181
+ console.log(chalk.dim(' Name: "<Original Name> - Logged In" (e.g. "Full Catalog - Logged In")'));
1182
+ console.log(chalk.dim(' Step 8 scenarios already serve as logged-out versions (no session cookie)'));
1183
+ checkbox('If there are multiple user roles (admin, regular, etc.), create role-specific variations too');
1184
+ console.log(chalk.dim(' Each persona scenario layers user-specific seed data on top of an app scenario'));
918
1185
  checkbox('After each registration, check the response for `clientErrors`');
919
1186
  console.log(chalk.yellow(' If clientErrors is non-empty → fix the issue and re-register the scenario'));
920
- console.log(chalk.yellow(' Fix client errors and re-register before moving on'));
921
1187
  console.log();
922
- console.log(chalk.bold('If the app has NO users:'));
923
- console.log(chalk.dim(' Skip this step and proceed to step 10 (Verify).'));
924
- console.log();
925
- console.log(chalk.dim('Focus on creating user-persona scenarios (or skip if no users). Code fixes happen in step 10 if needed.'));
1188
+ console.log(chalk.dim('See FEATURE_PATTERNS.md and AUTH_PATTERNS.md for auth scenario guidance.'));
926
1189
  stopGate(9);
927
1190
  }
928
1191
  // ─── Step 10: Verify ──────────────────────────────────────────────────
@@ -952,13 +1215,15 @@ function printStep10(root, feature) {
952
1215
  console.log(chalk.dim(` codeyam editor register '{"name":"ComponentName - Scenario",...}'`));
953
1216
  console.log();
954
1217
  console.log(chalk.bold('Editor scenarios (App tab) — visual + error check:'));
955
- checkbox(`Refresh the preview: \`curl -s -X POST http://localhost:${port}/api/editor-refresh\``);
1218
+ checkbox(`Refresh the preview: \`codeyam editor preview\``);
956
1219
  checkbox('Click through each app-level and user-persona scenario in the preview');
957
- checkbox(`Check for client-side errors: \`curl -s http://localhost:${port}/api/editor-client-errors\``);
1220
+ checkbox('For seed-based scenarios: verify data renders correctly after switching');
1221
+ console.log(chalk.dim(' Switch between scenarios and confirm the app reflects the seeded data each time'));
1222
+ checkbox(`Check for client-side errors: \`codeyam editor client-errors\``);
958
1223
  console.log(chalk.yellow(' If `hasErrors` is true: list each scenario with errors, fix the source code,'));
959
1224
  console.log(chalk.yellow(' re-register the affected scenarios, and re-check until hasErrors is false'));
960
1225
  console.log(chalk.dim(' Common errors: React errors, failed fetches, undefined references, hydration mismatches'));
961
- checkbox('Verify no broken images in any scenario screenshots');
1226
+ checkbox('Verify no broken images: `codeyam editor verify-images \'{"paths":["/"], "imageUrls":["url1"]}\'` with all page paths and image URLs');
962
1227
  console.log();
963
1228
  console.log(chalk.bold('Library functions — test check:'));
964
1229
  checkbox('Re-run all test files from step 5 to confirm they still pass');
@@ -991,16 +1256,13 @@ function printStep11(root, feature) {
991
1256
  console.log(chalk.bold('Checklist:'));
992
1257
  checkbox('Write a concise description of what was built (2-3 sentences)');
993
1258
  checkbox(`First time at step 11 — create journal entry with ALL session screenshots:`);
994
- console.log(chalk.dim(` curl -s -X POST http://localhost:${port}/api/editor-journal-entry \\`));
995
- console.log(chalk.dim(` -H 'Content-Type: application/json' \\`));
996
- console.log(chalk.dim(` -d '{"title":"...","type":"feature","description":"...","includeSessionScenarios":true}'`));
1259
+ console.log(chalk.dim(` codeyam editor journal '{"title":"...","type":"feature","description":"...","includeSessionScenarios":true}'`));
997
1260
  console.log(chalk.dim(' includeSessionScenarios auto-discovers component + app + user persona screenshots'));
998
- checkbox(`Returning after changes — update the existing journal entry:`);
999
- console.log(chalk.dim(` curl -s -X PATCH http://localhost:${port}/api/editor-journal-update \\`));
1000
- console.log(chalk.dim(` -H 'Content-Type: application/json' \\`));
1001
- console.log(chalk.dim(` -d '{"time":"<journal entry time>","description":"<updated>","includeSessionScenarios":true}'`));
1261
+ checkbox(`Returning to step 11 (before commit) — update the existing journal entry:`);
1262
+ console.log(chalk.dim(` codeyam editor journal-update '{"time":"<journal entry time>","description":"<updated>","includeSessionScenarios":true}'`));
1263
+ console.log(chalk.dim(' Note: PATCH only works before the entry is committed. After commit, use POST to create a new entry.'));
1002
1264
  console.log();
1003
- console.log(chalk.dim('Focus on creating or updating the journal entry. Summary and review happen in step 12.'));
1265
+ console.log(chalk.dim('Focus on creating or updating the journal entry. Summary and presentation happen in step 13.'));
1004
1266
  stopGate(11);
1005
1267
  }
1006
1268
  // ─── Step 12: Review ──────────────────────────────────────────────────
@@ -1021,52 +1283,154 @@ function printStep12(root, feature) {
1021
1283
  if (isResuming) {
1022
1284
  printResumptionHeader(12);
1023
1285
  }
1024
- console.log('Verify everything, then present the scenario table to the user.');
1286
+ console.log('Verify all screenshots and checks pass before presenting to the user.');
1025
1287
  console.log();
1026
- console.log(chalk.bold('Phase 1 — Verify (do all of this silently):'));
1027
- checkbox(`Refresh the preview: \`curl -s -X POST http://localhost:${port}/api/dev-mode-preview\``);
1288
+ console.log(chalk.bold('Checklist (do all of this silently):'));
1289
+ checkbox(`Refresh the preview: \`codeyam editor preview\``);
1028
1290
  checkbox('Verify each component has screenshots in the App tab (grouped under Components)');
1029
1291
  checkbox('If any are missing, re-register them using `codeyam editor register`');
1030
- checkbox(`Check for client errors: \`curl -s http://localhost:${port}/api/editor-client-errors\``);
1292
+ checkbox(`Check for client errors: \`codeyam editor client-errors\``);
1031
1293
  checkbox('If `hasErrors` is true, fix them and re-capture affected scenarios');
1294
+ checkbox('Run `codeyam editor verify-images \'{"paths":["/"], "imageUrls":["url1"]}\'` with all page paths and image URLs');
1295
+ checkbox('Fix or remove any broken images before continuing');
1032
1296
  checkbox('Run `codeyam editor audit` to verify completeness of scenarios and tests');
1033
1297
  checkbox('Do not proceed until all checks pass');
1298
+ stopGate(12);
1299
+ }
1300
+ // ─── Step 13: Present ─────────────────────────────────────────────────
1301
+ function printStep13(root, feature) {
1302
+ const port = getServerPort();
1303
+ const prevState = readState(root);
1304
+ const isResuming = prevState?.step === 13;
1305
+ const now = new Date().toISOString();
1306
+ writeState(root, {
1307
+ feature,
1308
+ step: 13,
1309
+ label: STEP_LABELS[13],
1310
+ startedAt: isResuming ? prevState.startedAt : now,
1311
+ featureStartedAt: prevState?.featureStartedAt || now,
1312
+ });
1313
+ logEvent(root, 'step', { step: 13, label: 'Present', feature });
1314
+ stepHeader(13, 'Present', feature);
1315
+ if (isResuming) {
1316
+ printResumptionHeader(13);
1317
+ }
1318
+ console.log('Present the results to the user and get their approval.');
1034
1319
  console.log();
1035
- console.log(chalk.bold('Phase 2 — Present to the user:'));
1036
- checkbox('Write a 1-2 sentence summary of what was built');
1037
- checkbox('Report test count and audit status (one line)');
1038
- checkbox('Switch the active scenario to the best demo state for the feature:');
1039
- console.log(chalk.dim(` curl -s -X POST http://localhost:${port}/api/dev-mode-preview \\`));
1040
- console.log(chalk.dim(` -H 'Content-Type: application/json' -d '{"scenarioSlug":"...","scenarioId":"..."}'`));
1041
- checkbox(`Show the results panel: \`curl -s -X POST http://localhost:${port}/api/editor-show-results\``);
1320
+ console.log(chalk.bold('Checklist:'));
1321
+ checkbox('Fetch all scenarios: `codeyam editor scenarios`');
1322
+ console.log(chalk.dim(' Each scenario has a `changeStatus` field: "new", "edited", "impacted", or null.'));
1323
+ checkbox('Pick the best scenario to showcase from this working session:');
1324
+ console.log(chalk.dim(' Prefer scenarios with changeStatus "new" or "edited" (directly changed in this session).'));
1325
+ console.log(chalk.dim(' For app-level scenarios, prefer those showing the new/changed functionality.'));
1326
+ console.log(chalk.dim(' NEVER pick a scenario with changeStatus null those are unchanged from a previous commit.'));
1327
+ checkbox('Switch the preview to that scenario using its `id`:');
1328
+ console.log(chalk.dim(` codeyam editor preview '{"scenarioId":"<id>"}'`));
1329
+ checkbox(`Show the results panel: \`codeyam editor show-results\``);
1042
1330
  console.log(chalk.dim(' This opens a visual panel below the terminal showing all scenarios with screenshots.'));
1043
1331
  console.log(chalk.dim(' The user can click scenarios to switch the live preview.'));
1332
+ checkbox('Write a 1-2 sentence summary of what was built');
1333
+ checkbox('Report test count and audit status (one line)');
1044
1334
  console.log();
1045
- console.log(chalk.bold('Phase 3 — Present a selection menu to the user (use AskUserQuestion):'));
1046
- console.log(chalk.green(' "Save & commit"') +
1335
+ console.log(chalk.bold('Present a selection menu to the user (use AskUserQuestion with these EXACT option labels):'));
1336
+ console.log(chalk.green(' Option 1 label: "Save & commit"') +
1047
1337
  chalk.dim(' — git commit all changes and record in journal'));
1048
- console.log(chalk.yellow(' "I\'d like to make some changes"') +
1338
+ console.log(chalk.yellow(' Option 2 label: "I\'d like to make some changes"') +
1049
1339
  chalk.dim(' — describe changes, then re-verify'));
1050
1340
  console.log();
1051
1341
  console.log(chalk.bold('If the user chooses "Save & commit":'));
1052
- checkbox(`Git commit using the journal description: \`curl -s -X POST http://localhost:${port}/api/editor-commit -H 'Content-Type: application/json' -d '{"message":"feat: <title>\\n\\n<journal description>"}'\``);
1342
+ checkbox('Advance to the commit step: `codeyam editor 14`');
1343
+ console.log();
1344
+ console.log(chalk.bold('If the user chooses "Make changes" (or asks for ANY change, even as a question):'));
1345
+ checkbox(`Hide the results panel: \`codeyam editor hide-results\``);
1346
+ checkbox('Ask what changes the user wants (if not already clear)');
1347
+ checkbox(`Run: \`codeyam editor change "${feature}"\` — this gives you the change checklist`);
1348
+ checkbox('THEN make the requested changes and follow the checklist');
1349
+ console.log(chalk.red.bold(' IMPORTANT: Always run the change command BEFORE writing any code.'));
1350
+ stopGate(13, { confirm: true });
1351
+ }
1352
+ // ─── Step 14: Commit ─────────────────────────────────────────────────
1353
+ function printStep14(root, feature) {
1354
+ const prevState = readState(root);
1355
+ const isResuming = prevState?.step === 14;
1356
+ const now = new Date().toISOString();
1357
+ writeState(root, {
1358
+ feature,
1359
+ step: 14,
1360
+ label: STEP_LABELS[14],
1361
+ startedAt: isResuming ? prevState.startedAt : now,
1362
+ featureStartedAt: prevState?.featureStartedAt || now,
1363
+ });
1364
+ logEvent(root, 'step', { step: 14, label: 'Commit', feature });
1365
+ stepHeader(14, 'Commit', feature);
1366
+ if (isResuming) {
1367
+ printResumptionHeader(14);
1368
+ }
1369
+ console.log('Commit all changes for this feature.');
1370
+ console.log();
1371
+ console.log(chalk.bold('Checklist:'));
1372
+ checkbox(`Hide the results panel: \`codeyam editor hide-results\``);
1373
+ checkbox(`Git commit using the journal description: \`codeyam editor commit '{"message":"feat: <title>\\n\\n<journal description>"}'\``);
1053
1374
  console.log(chalk.dim(' The commit message body MUST match the journal description exactly'));
1054
- checkbox(`Update journal 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: <title>"}'\``);
1055
- console.log(chalk.green(' Then run: ') +
1056
- chalk.bold('codeyam editor 1') +
1057
- chalk.green(' to start the next feature'));
1058
- console.log();
1059
- console.log(chalk.bold('If the user chooses "Make changes":'));
1060
- checkbox('Ask what changes the user wants');
1061
- checkbox('Make the requested changes');
1062
- console.log(chalk.yellow(' Then run: ') +
1063
- chalk.bold(`codeyam editor change "${feature}"`) +
1064
- chalk.yellow(' — this prints a post-change checklist to re-register scenarios,'));
1065
- console.log(chalk.yellow(' re-run tests, update journal screenshots, and loop back to this review step.'));
1066
- console.log(chalk.red.bold(' IMPORTANT: You MUST run the change command. Do not skip this or try to re-verify manually.'));
1067
- console.log();
1068
- console.log(chalk.dim('Complete all phases in order: summary, screenshot verification, user menu.'));
1069
- stopGate(12, { confirm: true });
1375
+ stopGate(14);
1376
+ }
1377
+ // ─── Step 15: Finalize ───────────────────────────────────────────────
1378
+ function printStep15(root, feature) {
1379
+ const prevState = readState(root);
1380
+ const isResuming = prevState?.step === 15;
1381
+ const now = new Date().toISOString();
1382
+ writeState(root, {
1383
+ feature,
1384
+ step: 15,
1385
+ label: STEP_LABELS[15],
1386
+ startedAt: isResuming ? prevState.startedAt : now,
1387
+ featureStartedAt: prevState?.featureStartedAt || now,
1388
+ });
1389
+ logEvent(root, 'step', { step: 15, label: 'Finalize', feature });
1390
+ stepHeader(15, 'Finalize', feature);
1391
+ if (isResuming) {
1392
+ printResumptionHeader(15);
1393
+ }
1394
+ console.log('Update the journal with the commit SHA and amend the commit.');
1395
+ console.log();
1396
+ console.log(chalk.bold('Checklist:'));
1397
+ checkbox(`Update journal with commit SHA: \`codeyam editor journal-update '{"time":"<journal entry time>","commitSha":"<sha>","commitMessage":"feat: <title>"}'\``);
1398
+ checkbox('Amend the commit to include the journal update: `git add .codeyam/journal/ && git commit --amend --no-edit`');
1399
+ console.log(chalk.dim(' The journal-update modifies journal files after the commit — amend to keep the tree clean.'));
1400
+ stopGate(15);
1401
+ }
1402
+ // ─── Step 16: Push ───────────────────────────────────────────────────
1403
+ function printStep16(root, feature) {
1404
+ const prevState = readState(root);
1405
+ const isResuming = prevState?.step === 16;
1406
+ const now = new Date().toISOString();
1407
+ writeState(root, {
1408
+ feature,
1409
+ step: 16,
1410
+ label: STEP_LABELS[16],
1411
+ startedAt: isResuming ? prevState.startedAt : now,
1412
+ featureStartedAt: prevState?.featureStartedAt || now,
1413
+ });
1414
+ logEvent(root, 'step', { step: 16, label: 'Push', feature });
1415
+ stepHeader(16, 'Push', feature);
1416
+ if (isResuming) {
1417
+ printResumptionHeader(16);
1418
+ }
1419
+ console.log('Push the commit to the remote repository.');
1420
+ console.log();
1421
+ console.log(chalk.bold('Checklist:'));
1422
+ checkbox('Check if a git remote is configured: `git remote -v`');
1423
+ checkbox("Offer to push to remote (AskUserQuestion — STOP and wait for the user's answer before proceeding):");
1424
+ console.log(chalk.dim(' If a remote exists, ask (AskUserQuestion): "Would you like me to push this commit to the remote?" with options "Yes, push" and "No, skip"'));
1425
+ console.log(chalk.dim(' If the user says yes, run: `git push`'));
1426
+ console.log(chalk.dim(' If NO remote exists, ask (AskUserQuestion): "This project doesn\'t have a git remote yet. Would you like help setting one up? I can walk you through creating a GitHub repository." with options "Yes, set up remote" and "No, skip"'));
1427
+ console.log(chalk.dim(' If the user wants help, guide them through `gh repo create` or manual GitHub setup, then push.'));
1428
+ checkbox('After the user responds, run: `codeyam editor steps` to start the next feature');
1429
+ console.log();
1430
+ console.log(chalk.red.bold(' If the user reports a bug or requests a fix after committing:'));
1431
+ console.log(chalk.red.bold(' You MUST still run `codeyam editor change` before making any changes.'));
1432
+ console.log(chalk.red.bold(' The change workflow applies to ALL changes — post-commit fixes are not an exception.'));
1433
+ stopGate(16, { confirm: true });
1070
1434
  }
1071
1435
  // ─── Command definition ───────────────────────────────────────────────
1072
1436
  // ─── Analyze-imports subcommand ────────────────────────────────────────
@@ -1076,11 +1440,15 @@ function printStep12(root, feature) {
1076
1440
  * Runs data-structure-only analysis for all glossary entities, then outputs
1077
1441
  * an import graph and entity data structures as JSON to stdout.
1078
1442
  */
1079
- async function handleAnalyzeImports() {
1443
+ async function handleAnalyzeImports(options = {}) {
1080
1444
  const root = getProjectRoot();
1081
1445
  // Read glossary
1082
1446
  const glossaryPath = path.join(root, '.codeyam', 'glossary.json');
1083
1447
  if (!fs.existsSync(glossaryPath)) {
1448
+ if (options.silent) {
1449
+ // Internal caller — glossary doesn't exist yet, nothing to analyze
1450
+ return;
1451
+ }
1084
1452
  console.error(chalk.red('Error: .codeyam/glossary.json not found.'));
1085
1453
  console.error(chalk.dim(' Run codeyam editor 6 to create the glossary first.'));
1086
1454
  process.exit(1);
@@ -1098,15 +1466,24 @@ async function handleAnalyzeImports() {
1098
1466
  process.exit(1);
1099
1467
  }
1100
1468
  const filePaths = glossaryEntries.map((e) => e.filePath);
1101
- const entityNames = glossaryEntries.map((e) => e.name);
1469
+ // Include page files so pages get analyzed as entities too.
1470
+ // This allows the import graph to map page names to their dependencies.
1471
+ const { scanPageFilePaths } = await import('../utils/entityChangeStatus.server.js');
1472
+ const pageFilePaths = scanPageFilePaths(root);
1473
+ for (const pageFile of Object.values(pageFilePaths)) {
1474
+ if (!filePaths.includes(pageFile)) {
1475
+ filePaths.push(pageFile);
1476
+ }
1477
+ }
1102
1478
  const progress = new ProgressReporter();
1103
- // Run data-structure-only analysis for all entities
1104
- progress.start('Running import analysis for all glossary entities...');
1479
+ // Run data-structure-only analysis for all entities (glossary + pages)
1480
+ // Don't pass entityNames entities may not exist yet (fresh clone).
1481
+ // The analyzer will discover and create them from file paths.
1482
+ progress.start('Running import analysis for all entities...');
1105
1483
  try {
1106
1484
  await runAnalysisForEntities({
1107
1485
  projectRoot: root,
1108
1486
  filePaths,
1109
- entityNames,
1110
1487
  progress,
1111
1488
  onlyDataStructure: true,
1112
1489
  });
@@ -1123,8 +1500,11 @@ async function handleAnalyzeImports() {
1123
1500
  await initializeEnvironment();
1124
1501
  const entities = await loadEntities({});
1125
1502
  if (!entities || entities.length === 0) {
1126
- progress.fail('No entities found in database');
1127
- process.exit(1);
1503
+ progress.succeed('No entities found in database yet — skipping import analysis. This is normal on the first feature.');
1504
+ if (!options.silent) {
1505
+ console.log(JSON.stringify({ imports: {}, entities: {} }));
1506
+ }
1507
+ return;
1128
1508
  }
1129
1509
  // Deduplicate to latest versions
1130
1510
  const latestByKey = new Map();
@@ -1138,7 +1518,7 @@ async function handleAnalyzeImports() {
1138
1518
  latestByKey.set(key, entity);
1139
1519
  }
1140
1520
  }
1141
- const entityNameSet = new Set(entityNames);
1521
+ const entityNameSet = new Set(glossaryEntries.map((e) => e.name));
1142
1522
  const latestEntities = [...latestByKey.values()].filter((e) => entityNameSet.has(e.name));
1143
1523
  // Build import graph from importedExports metadata
1144
1524
  const imports = {};
@@ -1176,11 +1556,211 @@ async function handleAnalyzeImports() {
1176
1556
  };
1177
1557
  }
1178
1558
  progress.succeed('Done');
1179
- // Output combined JSON
1180
- const output = { imports, entities: entityData };
1181
- console.log(JSON.stringify(output, null, 2));
1559
+ // Output combined JSON (suppressed when called internally during startup)
1560
+ if (!options.silent) {
1561
+ const summary = formatApiSubcommandResult('analyze-imports', {
1562
+ imports,
1563
+ entities: entityData,
1564
+ });
1565
+ console.log(summary || JSON.stringify({ imports, entities: entityData }));
1566
+ }
1567
+ }
1568
+ // ─── Validate-seed subcommand ─────────────────────────────────────────
1569
+ /**
1570
+ * Validate seed data structure and check for a seed adapter.
1571
+ * Usage: codeyam editor validate-seed '{"products":[...]}'
1572
+ */
1573
+ function handleValidateSeed(jsonArg) {
1574
+ const root = process.cwd();
1575
+ // Check for seed adapter
1576
+ const adapterPath = detectSeedAdapter(root);
1577
+ if (adapterPath) {
1578
+ console.log(chalk.green(`Seed adapter found: ${adapterPath}`));
1579
+ }
1580
+ else {
1581
+ console.log(chalk.yellow('No seed adapter found. Create .codeyam/seed-adapter.ts to use seed-based scenarios.'));
1582
+ }
1583
+ if (!jsonArg) {
1584
+ return;
1585
+ }
1586
+ let data;
1587
+ try {
1588
+ data = JSON.parse(jsonArg);
1589
+ }
1590
+ catch {
1591
+ console.error(chalk.red('Error: Invalid JSON.'));
1592
+ process.exit(1);
1593
+ }
1594
+ const result = validateSeedData(data);
1595
+ if (result.valid) {
1596
+ const tables = Object.keys(data);
1597
+ const totalRows = tables.reduce((sum, t) => sum + (Array.isArray(data[t]) ? data[t].length : 0), 0);
1598
+ console.log(chalk.green(`Seed data valid: ${tables.length} table(s), ${totalRows} total row(s)`));
1599
+ for (const table of tables) {
1600
+ const rows = Array.isArray(data[table])
1601
+ ? data[table].length
1602
+ : 0;
1603
+ console.log(chalk.dim(` ${table}: ${rows} row(s)`));
1604
+ }
1605
+ }
1606
+ else {
1607
+ console.error(chalk.red('Seed data validation failed:'));
1608
+ for (const err of result.errors) {
1609
+ console.error(chalk.red(` - ${err}`));
1610
+ }
1611
+ process.exit(1);
1612
+ }
1613
+ }
1614
+ // ─── Isolate subcommand ───────────────────────────────────────────────
1615
+ /**
1616
+ * `codeyam editor isolate "StarRating CategoryBadge DrinkCard"`
1617
+ *
1618
+ * Creates isolation route directories and the layout guard file.
1619
+ * This avoids brace-expansion permission prompts in the embedded terminal.
1620
+ */
1621
+ function handleIsolate(componentNames) {
1622
+ const root = process.cwd();
1623
+ if (componentNames.length === 0) {
1624
+ console.error(chalk.red('Usage: codeyam editor isolate "ComponentA ComponentB ..."'));
1625
+ process.exit(1);
1626
+ }
1627
+ const isolateDir = path.join(root, 'app', 'isolated-components');
1628
+ // Create layout.tsx with production guard if missing
1629
+ const layoutPath = path.join(isolateDir, 'layout.tsx');
1630
+ if (!fs.existsSync(layoutPath)) {
1631
+ fs.mkdirSync(isolateDir, { recursive: true });
1632
+ fs.writeFileSync(layoutPath, [
1633
+ 'import { notFound } from "next/navigation";',
1634
+ '',
1635
+ 'export default function CaptureLayout({ children }: { children: React.ReactNode }) {',
1636
+ ' if (process.env.NODE_ENV === "production") notFound();',
1637
+ ' return <>{children}</>;',
1638
+ '}',
1639
+ '',
1640
+ ].join('\n'), 'utf8');
1641
+ console.log(chalk.green(`Created layout guard: app/isolated-components/layout.tsx`));
1642
+ }
1643
+ // Create a directory for each component
1644
+ const created = [];
1645
+ const existed = [];
1646
+ for (const name of componentNames) {
1647
+ const dir = path.join(isolateDir, name);
1648
+ if (fs.existsSync(dir)) {
1649
+ existed.push(name);
1650
+ }
1651
+ else {
1652
+ fs.mkdirSync(dir, { recursive: true });
1653
+ created.push(name);
1654
+ }
1655
+ }
1656
+ if (created.length > 0) {
1657
+ console.log(chalk.green(`Created ${created.length} isolation route dir(s): ${created.join(', ')}`));
1658
+ }
1659
+ if (existed.length > 0) {
1660
+ console.log(chalk.dim(`Already existed: ${existed.join(', ')}`));
1661
+ }
1182
1662
  }
1183
1663
  // ─── Register subcommand ──────────────────────────────────────────────
1664
+ /**
1665
+ * Format API subcommand results as concise one-line summaries.
1666
+ * Prevents Claude from piping output to python3 just to extract key fields.
1667
+ * Returns null for subcommands that should keep raw JSON output.
1668
+ */
1669
+ function formatApiSubcommandResult(subcommand, data) {
1670
+ if (!data || typeof data !== 'object')
1671
+ return null;
1672
+ switch (subcommand) {
1673
+ case 'journal': {
1674
+ const parts = [`success=${data.success}`];
1675
+ if (data.entry?.time)
1676
+ parts.push(`time="${data.entry.time}"`);
1677
+ if (data.entry?.title)
1678
+ parts.push(`title="${data.entry.title}"`);
1679
+ if (data.scenarioScreenshotsFound != null) {
1680
+ parts.push(`screenshots=${data.scenarioScreenshotsFound}`);
1681
+ }
1682
+ return parts.join(' ');
1683
+ }
1684
+ case 'journal-update': {
1685
+ const parts = [`success=${data.success}`];
1686
+ if (data.entry?.time)
1687
+ parts.push(`time="${data.entry.time}"`);
1688
+ if (data.scenarioScreenshotsFound != null) {
1689
+ parts.push(`screenshots=${data.scenarioScreenshotsFound}`);
1690
+ }
1691
+ return parts.join(' ');
1692
+ }
1693
+ case 'commit': {
1694
+ const parts = [`success=${data.success}`];
1695
+ if (data.sha)
1696
+ parts.push(`sha=${data.sha}`);
1697
+ if (data.message)
1698
+ parts.push(`message="${data.message.split('\n')[0]}"`);
1699
+ return parts.join(' ');
1700
+ }
1701
+ case 'preview': {
1702
+ const parts = [
1703
+ `success=${!!data.ok || data.success !== false}`,
1704
+ ];
1705
+ if (data.path)
1706
+ parts.push(`path="${data.path}"`);
1707
+ if (data.scenarioId)
1708
+ parts.push(`scenarioId="${data.scenarioId}"`);
1709
+ if (data.sessionsNotified != null)
1710
+ parts.push(`notified=${data.sessionsNotified}`);
1711
+ return parts.join(' ');
1712
+ }
1713
+ case 'dev-server': {
1714
+ if (data.status) {
1715
+ const parts = [`status=${data.status}`, `pid=${data.pid || 'none'}`];
1716
+ if (data.url)
1717
+ parts.push(`url=${data.url}`);
1718
+ if (data.proxyUrl)
1719
+ parts.push(`proxyUrl=${data.proxyUrl}`);
1720
+ if (data.errorMessage)
1721
+ parts.push(`error: ${data.errorMessage}`);
1722
+ return parts.join(' ');
1723
+ }
1724
+ return null;
1725
+ }
1726
+ case 'client-errors': {
1727
+ const parts = [`hasErrors=${data.hasErrors}`];
1728
+ parts.push(`totalErrors=${data.totalErrors ?? 0}`);
1729
+ if (data.livePreview) {
1730
+ const lp = data.livePreview;
1731
+ parts.push(`livePreview=${lp.loaded ? 'loaded' : 'not-loaded'}`);
1732
+ if (lp.loaded) {
1733
+ parts.push(`hasContent=${lp.hasContent}`);
1734
+ }
1735
+ const liveErrors = lp.errors?.length ?? 0;
1736
+ parts.push(`liveErrors=${liveErrors}`);
1737
+ if (liveErrors > 0) {
1738
+ // Show first few error messages for context
1739
+ for (const err of lp.errors.slice(0, 3)) {
1740
+ parts.push(` error: ${err.message}`);
1741
+ }
1742
+ }
1743
+ }
1744
+ else {
1745
+ parts.push('livePreview=not-loaded');
1746
+ }
1747
+ return parts.join(' ');
1748
+ }
1749
+ case 'analyze-imports': {
1750
+ const importEntries = Object.entries(data.imports || {});
1751
+ const entityEntries = Object.entries(data.entities || {});
1752
+ const parts = [];
1753
+ parts.push(`entities=${entityEntries.length}`);
1754
+ parts.push(`withImports=${importEntries.length}`);
1755
+ if (importEntries.length > 0) {
1756
+ parts.push(`imports: ${importEntries.map(([name, deps]) => `${name}→[${deps.join(',')}]`).join(' ')}`);
1757
+ }
1758
+ return parts.join(' ');
1759
+ }
1760
+ default:
1761
+ return null; // journal-list, show/hide-results: keep full JSON
1762
+ }
1763
+ }
1184
1764
  /**
1185
1765
  * `codeyam editor register '{"name":"...","componentName":"...",...}'`
1186
1766
  *
@@ -1190,18 +1770,19 @@ async function handleAnalyzeImports() {
1190
1770
  async function handleRegister(jsonArg) {
1191
1771
  if (!jsonArg) {
1192
1772
  console.error(chalk.red('Error: JSON argument required.'));
1193
- console.error(chalk.dim(' Usage: codeyam editor register \'{"name":"DrinkCard - Default","componentName":"DrinkCard","url":"/codeyam-isolate/DrinkCard?s=Default"}\''));
1773
+ console.error(chalk.dim(' Usage: codeyam editor register \'{"name":"DrinkCard - Default","componentName":"DrinkCard","url":"/isolated-components/DrinkCard?s=Default"}\''));
1774
+ console.error(chalk.dim(' For large payloads: codeyam editor register @/tmp/scenario.json'));
1194
1775
  process.exit(1);
1195
1776
  }
1196
- let body;
1197
- try {
1198
- body = JSON.parse(jsonArg);
1199
- }
1200
- catch {
1201
- console.error(chalk.red('Error: Invalid JSON.'));
1202
- console.error(chalk.dim(` Received: ${jsonArg.slice(0, 200)}`));
1777
+ const parsed = parseRegisterArg(jsonArg);
1778
+ if (parsed.error) {
1779
+ console.error(chalk.red(`Error: ${parsed.error}`));
1780
+ if (parsed.error === 'Invalid JSON') {
1781
+ console.error(chalk.dim(` Received: ${jsonArg.slice(0, 200)}`));
1782
+ }
1203
1783
  process.exit(1);
1204
1784
  }
1785
+ const body = parsed.body;
1205
1786
  const port = getServerPort();
1206
1787
  const url = `http://localhost:${port}/api/editor-register-scenario`;
1207
1788
  try {
@@ -1211,8 +1792,39 @@ async function handleRegister(jsonArg) {
1211
1792
  body: JSON.stringify(body),
1212
1793
  });
1213
1794
  const data = await res.json();
1214
- console.log(JSON.stringify(data, null, 2));
1795
+ // Print concise summary instead of raw JSON so Claude doesn't need python3
1796
+ const parts = [];
1797
+ parts.push(`success=${data.success}`);
1798
+ if (data.scenario?.name)
1799
+ parts.push(`name="${data.scenario.name}"`);
1800
+ parts.push(`screenshot=${!!data.screenshotCaptured}`);
1801
+ if (data.capturedViewport) {
1802
+ parts.push(`viewport=${data.capturedViewport.width}×${data.capturedViewport.height}`);
1803
+ }
1804
+ if (data.scenario?.dimension)
1805
+ parts.push(`dimension="${data.scenario.dimension}"`);
1806
+ if (data.clientErrors?.length > 0) {
1807
+ parts.push(chalk.red(`errors=${data.clientErrors.length}`));
1808
+ }
1809
+ else {
1810
+ parts.push(`errors=0`);
1811
+ }
1812
+ if (data.seedResult)
1813
+ parts.push(`seed=${data.seedResult.success}`);
1814
+ if (data.captureError)
1815
+ parts.push(chalk.yellow(`captureError="${data.captureError}"`));
1816
+ console.log(parts.join(' '));
1817
+ // Surface client errors prominently so they can't be missed
1818
+ if (data.clientErrors && data.clientErrors.length > 0) {
1819
+ console.log(chalk.red.bold(`⚠ WARNING: ${data.clientErrors.length} client error${data.clientErrors.length !== 1 ? 's' : ''} detected during capture:`));
1820
+ for (const err of data.clientErrors) {
1821
+ console.log(chalk.red(` → ${err}`));
1822
+ }
1823
+ console.log(chalk.yellow(' The screenshot may show an error screen instead of the actual component.'));
1824
+ console.log(chalk.yellow(' Fix the issue and re-register this scenario.'));
1825
+ }
1215
1826
  if (!res.ok) {
1827
+ console.error(chalk.dim(JSON.stringify(data, null, 2)));
1216
1828
  process.exit(1);
1217
1829
  }
1218
1830
  }
@@ -1241,11 +1853,23 @@ async function handleDependents(entityName) {
1241
1853
  const progress = new ProgressReporter();
1242
1854
  progress.start('Loading entities from database...');
1243
1855
  await initializeEnvironment();
1244
- const allEntities = await loadEntities({});
1856
+ let allEntities = await loadEntities({});
1245
1857
  if (!allEntities || allEntities.length === 0) {
1246
- progress.fail('No entities found in database');
1247
- console.error(chalk.dim(' Run codeyam editor analyze-imports first to populate entity data.'));
1248
- process.exit(1);
1858
+ progress.succeed('No entities found running analyze-imports first...');
1859
+ try {
1860
+ await handleAnalyzeImports({ silent: true });
1861
+ }
1862
+ catch {
1863
+ console.error(chalk.red('Could not build import graph. Run `codeyam editor analyze-imports` manually.'));
1864
+ process.exit(1);
1865
+ }
1866
+ // Reload entities after analysis
1867
+ const reloaded = await loadEntities({});
1868
+ if (!reloaded || reloaded.length === 0) {
1869
+ progress.fail('No entities found even after analyze-imports');
1870
+ process.exit(1);
1871
+ }
1872
+ allEntities = reloaded;
1249
1873
  }
1250
1874
  // Find the target entity by name (case-insensitive match)
1251
1875
  const targetEntities = allEntities.filter((e) => e.name.toLowerCase() === entityName.toLowerCase());
@@ -1332,15 +1956,15 @@ async function handleDependents(entityName) {
1332
1956
  * `codeyam editor change <feature>`
1333
1957
  *
1334
1958
  * Prints a condensed post-change checklist that guides Claude through
1335
- * re-verifying after user-requested modifications. This is the "change
1336
- * loop" it replaces the freeform "make changes" path with structured
1337
- * instructions that always loop back to step 12 review.
1959
+ * re-verifying after user-requested modifications. When called from
1960
+ * step 13+, this loops back to step 13 (present). When called from an
1961
+ * earlier step, it returns to that step so the normal flow continues.
1338
1962
  */
1339
1963
  function handleChange(feature) {
1340
1964
  const root = getProjectRoot();
1965
+ const state = readState(root);
1341
1966
  if (!feature) {
1342
1967
  // Try to read feature from state
1343
- const state = readState(root);
1344
1968
  if (state?.feature) {
1345
1969
  feature = state.feature;
1346
1970
  }
@@ -1350,6 +1974,7 @@ function handleChange(feature) {
1350
1974
  process.exit(1);
1351
1975
  }
1352
1976
  }
1977
+ const currentStep = state?.step ?? 13;
1353
1978
  const port = getServerPort();
1354
1979
  console.log();
1355
1980
  console.log(chalk.bold.cyan('━━━ Change Loop ━━━'));
@@ -1357,35 +1982,105 @@ function handleChange(feature) {
1357
1982
  console.log();
1358
1983
  console.log('The user has requested changes. Follow this checklist after making them.');
1359
1984
  console.log();
1985
+ const designSystem = readDesignSystem(root);
1986
+ if (designSystem) {
1987
+ console.log(chalk.bold.magenta('Design System (active):'));
1988
+ console.log(chalk.magenta(' Use existing CSS custom property tokens when making visual changes — no hardcoded px or hex values.'));
1989
+ console.log(chalk.magenta(' Use var(--text-sm) not 14, var(--spacing-lg) not 16px, var(--text-primary) not #1A1B25.'));
1990
+ console.log();
1991
+ console.log(designSystem);
1992
+ console.log();
1993
+ }
1994
+ console.log(chalk.bold.cyan('Keep the preview moving:'));
1995
+ console.log(chalk.cyan(` Refresh after EACH individual change — not after all changes are done:`));
1996
+ console.log(chalk.cyan(` codeyam editor preview`));
1997
+ console.log(chalk.cyan(' The user is watching the preview. Let them see progress incrementally.'));
1998
+ console.log();
1999
+ console.log(chalk.bold('0. Close the results panel:'));
2000
+ checkbox(`Hide results: \`codeyam editor hide-results\``);
2001
+ console.log();
1360
2002
  console.log(chalk.bold('1. Re-register affected component scenarios:'));
1361
2003
  checkbox('For each component you modified, re-register ALL its scenarios');
1362
- console.log(chalk.dim(` codeyam editor register '{"name":"ComponentName - ScenarioName","description":"...","componentName":"ComponentName","componentPath":"app/components/ComponentName.tsx"}'`));
1363
- checkbox('For any NEW components, create isolation routes and register scenarios');
2004
+ console.log(chalk.dim(` codeyam editor register '{"name":"ComponentName - ScenarioName","componentName":"ComponentName","componentPath":"app/components/ComponentName.tsx","url":"/isolated-components/ComponentName?s=ScenarioName"}'`));
2005
+ checkbox('For any NEW components: `codeyam editor isolate NewComponent` then create isolation routes and register scenarios');
1364
2006
  console.log();
1365
2007
  console.log(chalk.bold('2. Re-run affected tests:'));
1366
2008
  checkbox('Re-run test files for any functions you modified');
1367
2009
  console.log(chalk.dim(' Example: npx vitest run app/lib/drinks.test.ts'));
1368
2010
  checkbox('If any test fails, fix the source code and re-run');
2011
+ checkbox('If you re-seeded the database, restart the dev server to pick up fresh data');
2012
+ console.log(chalk.dim(` codeyam editor dev-server '{"action":"restart"}'`));
1369
2013
  console.log();
1370
2014
  console.log(chalk.bold('3. Re-capture app-level scenarios:'));
1371
- checkbox('If component changes affect app-level pages, re-register affected app scenarios');
1372
- checkbox(`Use \`codeyam editor dependents ComponentName\` to find what needs recapturing`);
2015
+ checkbox('For each changed component, run `codeyam editor dependents ComponentName` to find affected pages');
2016
+ checkbox('Run `codeyam editor scenarios` to list all existing scenarios');
2017
+ checkbox('For EACH page listed by dependents: find its existing scenarios in the list and re-register every one');
2018
+ console.log(chalk.dim(' Shared components (headers, navbars, layouts) affect MANY pages — re-register all of them.'));
2019
+ console.log(chalk.dim(' Re-register with the SAME name to update — do NOT create new/duplicate scenarios.'));
2020
+ console.log(chalk.dim(' Example: if Header changed and Home, Catalog, Detail pages use it,'));
2021
+ console.log(chalk.dim(' re-register "Home - Default", "Catalog - Full", "Detail - WithReviews", etc.'));
2022
+ checkbox("Enrich existing scenario data to exercise the change — don't just re-register unchanged data");
2023
+ console.log(chalk.dim(' Add data that demonstrates what changed: new fields, relationships, states, content variety.'));
2024
+ checkbox('After each re-registration, view the screenshot to verify data is visible');
2025
+ console.log(chalk.dim(" If the screenshot doesn't show the data you put in, the scenario is broken."));
1373
2026
  console.log();
1374
2027
  console.log(chalk.bold('4. Verify completeness:'));
1375
- checkbox(`Refresh the preview: \`curl -s -X POST http://localhost:${port}/api/dev-mode-preview\``);
1376
- checkbox(`Navigate to key pages to verify changes: \`curl -s -X POST http://localhost:${port}/api/dev-mode-preview -H 'Content-Type: application/json' -d '{"path":"/your-route"}'\``);
2028
+ checkbox(`Refresh the preview: \`codeyam editor preview\``);
2029
+ checkbox(`Navigate to key pages to verify changes: \`codeyam editor preview '{"path":"/your-route"}'\``);
2030
+ checkbox('Run `codeyam editor scenario-coverage` — all affected scenarios must be fresh');
1377
2031
  checkbox('Run `codeyam editor audit` — all checks must pass');
1378
- checkbox(`Check for client-side errors: \`curl -s http://localhost:${port}/api/editor-client-errors\``);
2032
+ checkbox(`Check for client-side errors: \`codeyam editor client-errors\``);
2033
+ console.log(chalk.dim(' If `hasContent=false`, the preview is blank — fix the code before proceeding.'));
2034
+ console.log(chalk.dim(' If `liveErrors>0`, there are JS errors in the preview — fix them.'));
1379
2035
  checkbox('Fix any errors, then re-register affected scenarios');
2036
+ checkbox('If changes affect setup, new dependencies, or new scripts: update `README.md` and `npm run setup`');
2037
+ console.log();
2038
+ console.log(chalk.bold('5. Update the existing journal entry:'));
2039
+ checkbox('Get existing entry: `codeyam editor journal-list`');
2040
+ checkbox('Find the uncommitted entry (commitSha is null) from this feature session');
2041
+ checkbox(`Update it: \`codeyam editor journal-update '{"time":"<entry time>","description":"<updated description including changes>","includeSessionScenarios":true}'\``);
2042
+ console.log(chalk.dim(' Always update the existing uncommitted entry — do NOT create a new one.'));
2043
+ console.log(chalk.dim(' Only create a new entry (POST) if no uncommitted entry exists for this feature.'));
2044
+ console.log();
2045
+ // If the change was initiated from a step before 13, return to that step
2046
+ // instead of jumping to step 13. The change workflow should only loop to
2047
+ // step 13 when changes are requested FROM step 13.
2048
+ if (currentStep < 13) {
2049
+ console.log(chalk.red(' ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'));
2050
+ console.log(chalk.red.bold(' REQUIRED: Return to current step'));
2051
+ console.log(chalk.red.bold(' When all checks pass, you MUST run: ') +
2052
+ chalk.bold(`codeyam editor ${currentStep}`));
2053
+ console.log(chalk.red(' ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'));
2054
+ }
2055
+ else {
2056
+ console.log(chalk.red(' ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'));
2057
+ console.log(chalk.red.bold(' REQUIRED: Show Results'));
2058
+ console.log(chalk.red.bold(' When all checks pass, you MUST run: ') +
2059
+ chalk.bold(`codeyam editor 13`));
2060
+ console.log(chalk.red.bold(' The user ALWAYS expects to see results after changes. DO NOT skip this step.'));
2061
+ console.log(chalk.red(' ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'));
2062
+ }
1380
2063
  console.log();
1381
- console.log(chalk.bold('5. Update the journal:'));
1382
- checkbox(`Update journal entry with new screenshots: \`curl -s -X PATCH http://localhost:${port}/api/editor-journal-update -H 'Content-Type: application/json' -d '{"time":"<journal entry time>","description":"<updated>","includeSessionScenarios":true}'\``);
1383
- console.log(chalk.dim(' includeSessionScenarios refreshes ALL screenshots to reflect the changes'));
1384
- console.log();
1385
- console.log(chalk.bold.green('When all checks pass, run: ') +
1386
- chalk.bold(`codeyam editor 12`));
1387
- console.log(chalk.dim(' This re-enters the review step to present the updated summary to the user.'));
1388
- console.log();
2064
+ }
2065
+ // ─── Audit gate ─────────────────────────────────────────────────────
2066
+ /**
2067
+ * Silently check whether the audit passes. Returns true if allPassing,
2068
+ * false if any issues remain or the server is unreachable.
2069
+ * Used as a hard gate before steps 8+.
2070
+ */
2071
+ async function checkAuditGate() {
2072
+ const port = getServerPort();
2073
+ try {
2074
+ const res = await fetch(`http://localhost:${port}/api/editor-audit`);
2075
+ if (!res.ok)
2076
+ return false;
2077
+ const data = await res.json();
2078
+ return data?.summary?.allPassing === true;
2079
+ }
2080
+ catch {
2081
+ // Server not running or unreachable — can't verify, so don't block
2082
+ return true;
2083
+ }
1389
2084
  }
1390
2085
  // ─── Audit subcommand ────────────────────────────────────────────────
1391
2086
  /**
@@ -1421,10 +2116,25 @@ async function handleAudit() {
1421
2116
  console.log(chalk.bold('Components (scenarios):'));
1422
2117
  for (const c of components) {
1423
2118
  const icon = c.status === 'ok' ? chalk.green('✓') : chalk.red('✗');
1424
- const count = c.status === 'ok'
1425
- ? chalk.dim(` (${c.scenarioCount} scenario${c.scenarioCount !== 1 ? 's' : ''})`)
1426
- : chalk.red('no scenarios registered');
1427
- console.log(` ${icon} ${c.name}${count}`);
2119
+ let detail;
2120
+ if (c.status === 'has_errors') {
2121
+ detail = chalk.red(`${c.scenarioCount} scenario${c.scenarioCount !== 1 ? 's' : ''} but has client errors`);
2122
+ }
2123
+ else if (c.status === 'ok') {
2124
+ detail = chalk.dim(` (${c.scenarioCount} scenario${c.scenarioCount !== 1 ? 's' : ''})`);
2125
+ }
2126
+ else {
2127
+ detail = chalk.red(' — no scenarios registered');
2128
+ }
2129
+ console.log(` ${icon} ${c.name}${detail}`);
2130
+ if (c.clientErrors && c.clientErrors.length > 0) {
2131
+ for (const err of c.clientErrors.slice(0, 3)) {
2132
+ console.log(chalk.red(` → ${err}`));
2133
+ }
2134
+ if (c.clientErrors.length > 3) {
2135
+ console.log(chalk.dim(` … and ${c.clientErrors.length - 3} more`));
2136
+ }
2137
+ }
1428
2138
  }
1429
2139
  console.log();
1430
2140
  }
@@ -1433,11 +2143,24 @@ async function handleAudit() {
1433
2143
  console.log(chalk.bold('Functions (test files):'));
1434
2144
  for (const f of functions) {
1435
2145
  const icon = f.status === 'ok' ? chalk.green('✓') : chalk.red('✗');
1436
- const detail = f.status === 'ok'
1437
- ? chalk.dim(` (${f.testFile})`)
1438
- : f.testFile
1439
- ? chalk.red(` — test file missing: ${f.testFile}`)
1440
- : chalk.red(' — no test file specified');
2146
+ let detail;
2147
+ switch (f.status) {
2148
+ case 'ok':
2149
+ detail = chalk.dim(` (${f.testFile})`);
2150
+ break;
2151
+ case 'failing':
2152
+ detail = chalk.red(` — tests failing: ${f.testFile}`);
2153
+ break;
2154
+ case 'name_mismatch':
2155
+ detail = chalk.red(` — tests pass but missing top-level describe("${f.name}", ...) — tests won't display in UI`);
2156
+ break;
2157
+ case 'missing':
2158
+ default:
2159
+ detail = f.testFile
2160
+ ? chalk.red(` — test file missing: ${f.testFile}`)
2161
+ : chalk.red(' — no test file specified');
2162
+ break;
2163
+ }
1441
2164
  console.log(` ${icon} ${f.name}${detail}`);
1442
2165
  }
1443
2166
  console.log();
@@ -1453,15 +2176,35 @@ async function handleAudit() {
1453
2176
  if (summary.componentsMissing > 0) {
1454
2177
  parts.push(`${summary.componentsMissing} component${summary.componentsMissing !== 1 ? 's' : ''} missing scenarios`);
1455
2178
  }
2179
+ if (summary.componentsWithErrors > 0) {
2180
+ parts.push(`${summary.componentsWithErrors} component${summary.componentsWithErrors !== 1 ? 's' : ''} with client errors`);
2181
+ }
1456
2182
  if (summary.functionsMissing > 0) {
1457
2183
  parts.push(`${summary.functionsMissing} function${summary.functionsMissing !== 1 ? 's' : ''} missing tests`);
1458
2184
  }
2185
+ if (summary.functionsFailing > 0) {
2186
+ parts.push(`${summary.functionsFailing} function${summary.functionsFailing !== 1 ? 's' : ''} with failing tests`);
2187
+ }
2188
+ if (summary.functionsNameMismatch > 0) {
2189
+ parts.push(`${summary.functionsNameMismatch} function${summary.functionsNameMismatch !== 1 ? 's' : ''} with test name mismatch (missing top-level describe)`);
2190
+ }
1459
2191
  console.log(chalk.red.bold('Audit failed: ') + parts.join(', '));
1460
2192
  }
1461
2193
  console.log();
1462
2194
  if (!allOk) {
1463
2195
  process.exit(1);
1464
2196
  }
2197
+ // Auto-run analyze-imports when audit passes — this builds the import graph
2198
+ // so the App tab can show component/function dependencies for each page.
2199
+ // Previously this was a manual step that Claude had to remember to run.
2200
+ console.log(chalk.dim('Building import graph...'));
2201
+ try {
2202
+ await handleAnalyzeImports({ silent: true });
2203
+ }
2204
+ catch {
2205
+ // Non-fatal — audit passed, import graph is a bonus
2206
+ console.log(chalk.yellow('Warning: Could not build import graph. Run `codeyam editor analyze-imports` manually.'));
2207
+ }
1465
2208
  }
1466
2209
  // ─── Scenarios subcommand ─────────────────────────────────────────────
1467
2210
  async function handleScenarios() {
@@ -1549,8 +2292,319 @@ async function handleScenarios() {
1549
2292
  const total = scenarios.length;
1550
2293
  const groupCount = groups.size;
1551
2294
  console.log(chalk.dim(`${total} scenario${total !== 1 ? 's' : ''} across ${groupCount} component${groupCount !== 1 ? 's' : ''}`));
2295
+ // Show screenshot paths so Claude can verify images with the Read tool
2296
+ const withScreenshots = scenarios.filter((s) => s.screenshotPath);
2297
+ if (withScreenshots.length > 0) {
2298
+ console.log();
2299
+ console.log(chalk.bold.cyan('Screenshots:'));
2300
+ for (const s of withScreenshots) {
2301
+ console.log(chalk.dim(` ${s.name}: ${s.screenshotPath}`));
2302
+ }
2303
+ }
2304
+ console.log();
2305
+ }
2306
+ // ─── Scenario Coverage subcommand ───────────────────────────────────
2307
+ async function handleScenarioCoverage() {
2308
+ const port = getServerPort();
2309
+ const url = `http://localhost:${port}/api/editor-scenario-coverage`;
2310
+ let data;
2311
+ try {
2312
+ const res = await fetch(url);
2313
+ if (!res.ok) {
2314
+ console.error(chalk.red(`Error: Scenario coverage endpoint returned ${res.status}`));
2315
+ process.exit(1);
2316
+ }
2317
+ data = await res.json();
2318
+ }
2319
+ catch (err) {
2320
+ console.error(chalk.red('Error: Could not reach the CodeYam server. Is it running?'));
2321
+ console.error(chalk.dim(` ${err.message}`));
2322
+ process.exit(1);
2323
+ }
2324
+ console.log();
2325
+ console.log(chalk.bold.cyan('━━━ Scenario Coverage ━━━'));
2326
+ console.log();
2327
+ if (data.note) {
2328
+ console.log(chalk.yellow(data.note));
2329
+ console.log();
2330
+ return;
2331
+ }
2332
+ // Fresh scenarios (already recaptured this feature)
2333
+ if (data.freshScenarios.length > 0) {
2334
+ console.log(chalk.green(`✓ ${data.freshScenarios.length} scenario(s) captured this feature:`));
2335
+ for (const s of data.freshScenarios) {
2336
+ console.log(chalk.dim(` ${s.name} (${s.url || '/'})`));
2337
+ }
2338
+ console.log();
2339
+ }
2340
+ // Stale scenarios (need recapturing)
2341
+ if (data.staleScenarios.length > 0) {
2342
+ console.log(chalk.red(`✗ ${data.staleScenarios.length} scenario(s) need re-registering (stale screenshots):`));
2343
+ for (const s of data.staleScenarios) {
2344
+ console.log(chalk.yellow(` ${s.name} (${s.url || '/'}) — ${s.changeStatus} but not recaptured`));
2345
+ }
2346
+ console.log();
2347
+ console.log(chalk.yellow('Re-register each stale scenario with the SAME name to update its screenshot.'));
2348
+ console.log(chalk.yellow("Enhance the seed data to reflect this feature's changes where relevant."));
2349
+ console.log();
2350
+ }
2351
+ // Uncovered pages (changed but no scenarios at all)
2352
+ if (data.uncoveredPages.length > 0) {
2353
+ console.log(chalk.red(`✗ ${data.uncoveredPages.length} page(s) affected by changes with no scenarios:`));
2354
+ for (const p of data.uncoveredPages) {
2355
+ console.log(chalk.yellow(` ${p.entityName} — ${p.changeStatus}`));
2356
+ }
2357
+ console.log();
2358
+ }
2359
+ // Summary
2360
+ if (data.pass) {
2361
+ console.log(chalk.green.bold('PASS — all affected scenarios are fresh'));
2362
+ }
2363
+ else {
2364
+ console.log(chalk.red.bold('FAIL — re-register stale scenarios before proceeding'));
2365
+ }
1552
2366
  console.log();
1553
2367
  }
2368
+ // ─── Template subcommand ─────────────────────────────────────────────
2369
+ async function handleTemplate() {
2370
+ const root = getProjectRoot();
2371
+ const port = getServerPort();
2372
+ if (hasProject(root)) {
2373
+ console.log(chalk.yellow('Project already exists (package.json found). Skipping.'));
2374
+ return;
2375
+ }
2376
+ // Determine which template to use from editor state
2377
+ const state = readState(root);
2378
+ const techStackId = state?.techStackId;
2379
+ const stack = techStackId
2380
+ ? TECH_STACKS.find((s) => s.id === techStackId)
2381
+ : undefined;
2382
+ const templateName = stack?.templateDir || 'nextjs-prisma-sqlite';
2383
+ const templateDir = path.join(__dirname, '..', '..', 'templates', templateName);
2384
+ if (!fs.existsSync(templateDir)) {
2385
+ console.error(chalk.red('Error: Template directory not found at ' + templateDir));
2386
+ process.exit(1);
2387
+ }
2388
+ const { execSync } = await import('child_process');
2389
+ // 1. Copy template files
2390
+ console.log(chalk.bold(`Copying ${stack?.name || templateName} template files...`));
2391
+ execSync(`cp -r ${templateDir}/* .`, { cwd: root, stdio: 'inherit' });
2392
+ // Copy dotfiles that are stored without the dot prefix in templates
2393
+ const gitignorePath = path.join(templateDir, 'gitignore');
2394
+ if (fs.existsSync(gitignorePath)) {
2395
+ execSync(`cp ${templateDir}/gitignore .gitignore`, {
2396
+ cwd: root,
2397
+ stdio: 'inherit',
2398
+ });
2399
+ }
2400
+ const envPath = path.join(templateDir, 'env');
2401
+ if (fs.existsSync(envPath)) {
2402
+ execSync(`cp ${templateDir}/env .env`, { cwd: root, stdio: 'inherit' });
2403
+ }
2404
+ // Copy seed adapter into .codeyam/ (stored outside .codeyam/ in the template
2405
+ // to avoid gitignore issues — .codeyam/ is selectively ignored in user projects)
2406
+ const seedAdapterSrc = path.join(templateDir, 'seed-adapter.ts');
2407
+ if (fs.existsSync(seedAdapterSrc)) {
2408
+ const codeyamDir = path.join(root, '.codeyam');
2409
+ if (!fs.existsSync(codeyamDir)) {
2410
+ fs.mkdirSync(codeyamDir, { recursive: true });
2411
+ }
2412
+ fs.copyFileSync(seedAdapterSrc, path.join(codeyamDir, 'seed-adapter.ts'));
2413
+ }
2414
+ console.log(chalk.green(' Template files copied.'));
2415
+ // 2. Install dependencies
2416
+ console.log(chalk.bold('Installing dependencies...'));
2417
+ execSync('npm install', { cwd: root, stdio: 'inherit' });
2418
+ console.log(chalk.green(' Dependencies installed.'));
2419
+ // 3. Initialize git
2420
+ const hasGit = fs.existsSync(path.join(root, '.git'));
2421
+ if (!hasGit) {
2422
+ console.log(chalk.bold('Initializing git...'));
2423
+ execSync('git init && git add -A && git commit -m "Initial commit"', {
2424
+ cwd: root,
2425
+ stdio: 'inherit',
2426
+ });
2427
+ console.log(chalk.green(' Git initialized.'));
2428
+ }
2429
+ // 4. Run codeyam init
2430
+ console.log(chalk.bold('Running codeyam init...'));
2431
+ await initCommand.handler({
2432
+ force: true,
2433
+ 'keep-server': true,
2434
+ autoInit: false,
2435
+ $0: '',
2436
+ _: [],
2437
+ });
2438
+ console.log(chalk.green(' CodeYam initialized.'));
2439
+ // 5. Verify config has startCommand
2440
+ const configPath = path.join(root, '.codeyam', 'config.json');
2441
+ if (fs.existsSync(configPath)) {
2442
+ try {
2443
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
2444
+ const webapps = config.webapps || [];
2445
+ const hasStartCommand = webapps.some((w) => w.startCommand);
2446
+ if (!hasStartCommand) {
2447
+ console.log(chalk.yellow(' Warning: No startCommand found in .codeyam/config.json webapps.'));
2448
+ console.log(chalk.dim(' You may need to add: "startCommand": { "command": "sh", "args": ["-c", "npm run dev -- --port $PORT"] }'));
2449
+ }
2450
+ }
2451
+ catch {
2452
+ // Config parse error is non-fatal
2453
+ }
2454
+ }
2455
+ // 5b. Write a fresh prototypeId so the proxy clears stale localStorage
2456
+ const activeScenarioPath = path.join(root, '.codeyam', 'active-scenario.json');
2457
+ fs.writeFileSync(activeScenarioPath, JSON.stringify({ prototypeId: Date.now().toString() }), 'utf-8');
2458
+ // 6. Trigger editor-refresh so the server picks up the new project
2459
+ console.log(chalk.bold('Refreshing editor...'));
2460
+ try {
2461
+ await fetch(`http://localhost:${port}/api/editor-refresh`, {
2462
+ method: 'POST',
2463
+ });
2464
+ console.log(chalk.green(' Editor refreshed.'));
2465
+ }
2466
+ catch {
2467
+ console.log(chalk.yellow(' Could not reach the CodeYam server for refresh. You may need to restart it.'));
2468
+ }
2469
+ console.log();
2470
+ console.log(chalk.green.bold('Project scaffolded and ready!'));
2471
+ console.log(chalk.dim('Next: Define your Prisma models, push the schema, seed the database, and build your feature.'));
2472
+ }
2473
+ // ─── Sync subcommand ─────────────────────────────────────────────────
2474
+ /**
2475
+ * `codeyam editor sync`
2476
+ * Import scenarios from editor-scenarios/ files into the local database.
2477
+ * Falls back to legacy scenarios-manifest.json if no _metadata files found.
2478
+ */
2479
+ async function handleSync() {
2480
+ const root = getProjectRoot();
2481
+ const entries = scanScenarioFiles(root);
2482
+ if (entries.length === 0) {
2483
+ console.log(chalk.yellow('No scenario files with metadata found. Nothing to sync.'));
2484
+ return;
2485
+ }
2486
+ const configPath = path.join(root, '.codeyam', 'config.json');
2487
+ let projectSlug = null;
2488
+ try {
2489
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
2490
+ projectSlug = config.projectSlug || null;
2491
+ }
2492
+ catch {
2493
+ // fall through
2494
+ }
2495
+ if (!projectSlug) {
2496
+ console.error(chalk.red('Error: No project slug found. Run codeyam init first.'));
2497
+ process.exit(1);
2498
+ }
2499
+ const connectionOk = await withoutSpinner(() => testEnvironment());
2500
+ if (!connectionOk) {
2501
+ errorLog('Environment validation failed');
2502
+ return;
2503
+ }
2504
+ const { project } = await requireBranchAndProject(projectSlug);
2505
+ const { getDatabase } = await import('../../../packages/database/index.js');
2506
+ const db = getDatabase();
2507
+ const existingRows = await db
2508
+ .selectFrom('editor_scenarios')
2509
+ .select(['id', 'updated_at'])
2510
+ .where('project_id', '=', project.id)
2511
+ .execute();
2512
+ const result = await syncScenarioFilesToDatabase(root, project.id, existingRows, async (row) => {
2513
+ await db
2514
+ .insertInto('editor_scenarios')
2515
+ .values(row)
2516
+ .execute();
2517
+ }, async (id, row) => {
2518
+ await db
2519
+ .updateTable('editor_scenarios')
2520
+ .set(row)
2521
+ .where('id', '=', id)
2522
+ .execute();
2523
+ });
2524
+ if (result.inserted === 0 && result.updated === 0) {
2525
+ console.log(chalk.dim('All scenarios up to date.'));
2526
+ }
2527
+ else {
2528
+ const parts = [];
2529
+ if (result.inserted > 0)
2530
+ parts.push(`${result.inserted} imported`);
2531
+ if (result.updated > 0)
2532
+ parts.push(`${result.updated} updated`);
2533
+ if (result.skipped > 0)
2534
+ parts.push(`${result.skipped} unchanged`);
2535
+ console.log(chalk.green(`Synced scenarios: ${parts.join(', ')}`));
2536
+ }
2537
+ }
2538
+ // ─── Verify Images subcommand ─────────────────────────────────────────
2539
+ async function handleVerifyImages(jsonArg) {
2540
+ const port = getServerPort();
2541
+ const { parseVerifyImagesInput, extractImageUrls, resolveImageUrl, verifyImageUrls, buildVerifyImagesReport, extractImageUrlsFromScenarioFiles, } = await import('../utils/editorImageVerifier.js');
2542
+ let paths;
2543
+ let explicitImageUrls;
2544
+ try {
2545
+ const input = parseVerifyImagesInput(jsonArg);
2546
+ paths = input.paths;
2547
+ explicitImageUrls = input.imageUrls;
2548
+ }
2549
+ catch {
2550
+ console.error(chalk.red('Error: Invalid JSON argument'));
2551
+ process.exit(1);
2552
+ }
2553
+ // Get dev server URL
2554
+ let devServerUrl;
2555
+ try {
2556
+ const res = await fetch(`http://localhost:${port}/api/editor-dev-server`);
2557
+ const data = await res.json();
2558
+ devServerUrl = data.url || `http://localhost:${data.port || 3000}`;
2559
+ }
2560
+ catch {
2561
+ console.error(chalk.red('Error: Could not reach the CodeYam server. Is it running?'));
2562
+ process.exit(1);
2563
+ }
2564
+ const allUrls = new Set();
2565
+ let pagesChecked = 0;
2566
+ for (const pagePath of paths) {
2567
+ const pageUrl = `${devServerUrl}${pagePath}`;
2568
+ try {
2569
+ const res = await fetch(pageUrl);
2570
+ if (!res.ok) {
2571
+ console.error(chalk.red(` ✗ ${pagePath} — HTTP ${res.status}`));
2572
+ continue;
2573
+ }
2574
+ const html = await res.text();
2575
+ const imageUrls = extractImageUrls(html);
2576
+ for (const url of imageUrls) {
2577
+ allUrls.add(resolveImageUrl(url, devServerUrl));
2578
+ }
2579
+ pagesChecked++;
2580
+ }
2581
+ catch (err) {
2582
+ console.error(chalk.red(` ✗ ${pagePath} — ${err.message}`));
2583
+ }
2584
+ }
2585
+ // Add explicitly-provided image URLs (Claude passes these directly)
2586
+ for (const url of explicitImageUrls) {
2587
+ allUrls.add(resolveImageUrl(url, devServerUrl));
2588
+ }
2589
+ // Also scan scenario mock data files for image URLs (client-rendered pages)
2590
+ const scenariosDir = path.join(getProjectRoot(), '.codeyam', 'editor-scenarios');
2591
+ const { urls: scenarioUrls, filesScanned: scenarioFilesScanned } = extractImageUrlsFromScenarioFiles(scenariosDir);
2592
+ for (const url of scenarioUrls) {
2593
+ allUrls.add(resolveImageUrl(url, devServerUrl));
2594
+ }
2595
+ const urlList = [...allUrls];
2596
+ const results = urlList.length > 0 ? await verifyImageUrls(urlList) : [];
2597
+ const report = buildVerifyImagesReport({
2598
+ pagesChecked,
2599
+ imageUrls: urlList,
2600
+ results,
2601
+ scenarioFilesScanned,
2602
+ });
2603
+ console.log(JSON.stringify(report, null, 2));
2604
+ if (report.failures.length > 0) {
2605
+ process.exit(1);
2606
+ }
2607
+ }
1554
2608
  // ─── Debug subcommand ────────────────────────────────────────────────
1555
2609
  function handleEditorDebug(args) {
1556
2610
  const root = getProjectRoot();
@@ -1611,8 +2665,12 @@ function handleEditorDebug(args) {
1611
2665
  10: printStep10,
1612
2666
  11: printStep11,
1613
2667
  12: printStep12,
2668
+ 13: printStep13,
2669
+ 14: printStep14,
2670
+ 15: printStep15,
2671
+ 16: printStep16,
1614
2672
  };
1615
- for (let step = 1; step <= 12; step++) {
2673
+ for (let step = 1; step <= 16; step++) {
1616
2674
  const stepId = `step-${step}`;
1617
2675
  if (!wants(stepId))
1618
2676
  continue;
@@ -1691,8 +2749,8 @@ const editorCommand = {
1691
2749
  describe: 'Editor mode guided workflow',
1692
2750
  builder: (yargs) => {
1693
2751
  const stepDescription = IS_INTERNAL_BUILD
1694
- ? 'Step number (1-12) or subcommand (register, analyze-imports, dependents, audit, scenarios, change, debug)'
1695
- : 'Step number (1-12) or subcommand (register, analyze-imports, dependents, audit, scenarios, change)';
2752
+ ? 'Step number (1-16) or subcommand (template, register, isolate, analyze-imports, dependents, audit, scenarios, scenario-coverage, change, sync, debug, preview, show-results, hide-results, commit, journal, journal-list, journal-update, dev-server, client-errors)'
2753
+ : 'Step number (1-16) or subcommand (template, register, isolate, analyze-imports, dependents, audit, scenarios, scenario-coverage, change, sync, preview, show-results, hide-results, commit, journal, journal-list, journal-update, dev-server, client-errors)';
1696
2754
  let builder = yargs
1697
2755
  .positional('step', {
1698
2756
  type: 'string',
@@ -1705,12 +2763,30 @@ const editorCommand = {
1705
2763
  .option('feature', {
1706
2764
  type: 'string',
1707
2765
  describe: 'Feature name (required for step 2)',
2766
+ })
2767
+ .option('app-formats', {
2768
+ type: 'string',
2769
+ describe: 'Comma-separated app formats (mobile-responsive-web-app, desktop-app, mobile-app)',
2770
+ })
2771
+ .option('tech-stack', {
2772
+ type: 'string',
2773
+ describe: 'Selected tech stack ID (e.g., nextjs-prisma-sqlite)',
2774
+ })
2775
+ .option('prompt', {
2776
+ type: 'string',
2777
+ describe: "User's original prompt (captured for journal/results)",
2778
+ })
2779
+ .option('port', {
2780
+ type: 'number',
2781
+ alias: 'p',
2782
+ describe: 'Port to run the web server on',
2783
+ default: 3111,
1708
2784
  });
1709
2785
  if (IS_INTERNAL_BUILD) {
1710
2786
  builder = builder
1711
2787
  .option('target', {
1712
2788
  type: 'string',
1713
- describe: 'Debug target (setup, overview, overview-with-state, step-1..step-12, or comma-separated list)',
2789
+ describe: 'Debug target (setup, overview, overview-with-state, step-1..step-16, or comma-separated list)',
1714
2790
  })
1715
2791
  .option('resume', {
1716
2792
  type: 'boolean',
@@ -1730,6 +2806,36 @@ const editorCommand = {
1730
2806
  },
1731
2807
  handler: async (argv) => {
1732
2808
  const root = getProjectRoot();
2809
+ // API subcommands: preview, show-results, hide-results, commit,
2810
+ // journal, journal-update, dev-server, client-errors
2811
+ if (argv.step && EDITOR_API_SUBCOMMANDS.includes(argv.step)) {
2812
+ const port = getServerPort();
2813
+ try {
2814
+ const request = buildEditorApiRequest(argv.step, argv.json || undefined);
2815
+ const result = await callEditorApi(request, port);
2816
+ if (!result.ok) {
2817
+ console.error(chalk.red(`Error: ${request.endpoint} returned ${result.status}`));
2818
+ if (result.data)
2819
+ console.error(JSON.stringify(result.data, null, 2));
2820
+ process.exit(1);
2821
+ }
2822
+ if (result.data != null) {
2823
+ const summary = formatApiSubcommandResult(argv.step, result.data);
2824
+ if (summary) {
2825
+ console.log(summary);
2826
+ }
2827
+ else {
2828
+ console.log(JSON.stringify(result.data, null, 2));
2829
+ }
2830
+ }
2831
+ }
2832
+ catch (err) {
2833
+ console.error(chalk.red('Error: Could not reach the CodeYam server. Is it running?'));
2834
+ console.error(chalk.dim(` ${err.message}`));
2835
+ process.exit(1);
2836
+ }
2837
+ return;
2838
+ }
1733
2839
  // Subcommand: codeyam editor register '{"name":"..."}'
1734
2840
  if (argv.step === 'register') {
1735
2841
  await handleRegister(argv.json || '');
@@ -1755,11 +2861,47 @@ const editorCommand = {
1755
2861
  await handleScenarios();
1756
2862
  return;
1757
2863
  }
2864
+ // Subcommand: codeyam editor scenario-coverage
2865
+ if (argv.step === 'scenario-coverage') {
2866
+ await handleScenarioCoverage();
2867
+ return;
2868
+ }
1758
2869
  // Subcommand: codeyam editor change <feature>
1759
2870
  if (argv.step === 'change') {
1760
2871
  handleChange(argv.json || '');
1761
2872
  return;
1762
2873
  }
2874
+ // Subcommand: codeyam editor verify-images '{"paths":["/","/drinks/1"]}'
2875
+ if (argv.step === 'verify-images') {
2876
+ await handleVerifyImages(argv.json || '');
2877
+ return;
2878
+ }
2879
+ // Subcommand: codeyam editor validate-seed '{"products":[...]}'
2880
+ if (argv.step === 'validate-seed') {
2881
+ await handleValidateSeed(argv.json || '');
2882
+ return;
2883
+ }
2884
+ // Subcommand: codeyam editor isolate "StarRating CategoryBadge DrinkCard"
2885
+ if (argv.step === 'isolate') {
2886
+ const names = [];
2887
+ if (argv.json)
2888
+ names.push(...argv.json.split(/[\s,]+/).filter(Boolean));
2889
+ // Collect any extra positional args (yargs puts them in argv._)
2890
+ const extras = argv._.filter((a) => typeof a === 'string' && a !== 'editor');
2891
+ names.push(...extras);
2892
+ handleIsolate(names);
2893
+ return;
2894
+ }
2895
+ // Subcommand: codeyam editor template — scaffold project from template
2896
+ if (argv.step === 'template') {
2897
+ await handleTemplate();
2898
+ return;
2899
+ }
2900
+ // Subcommand: codeyam editor sync — import scenarios from manifest
2901
+ if (argv.step === 'sync') {
2902
+ await handleSync();
2903
+ return;
2904
+ }
1763
2905
  // Subcommand: codeyam editor debug [--target ...]
1764
2906
  if (argv.step === 'debug') {
1765
2907
  if (!IS_INTERNAL_BUILD) {
@@ -1769,27 +2911,244 @@ const editorCommand = {
1769
2911
  await handleEditorDebug(argv);
1770
2912
  return;
1771
2913
  }
1772
- const step = argv.step ? parseInt(argv.step, 10) : undefined;
1773
- if (step != null && (isNaN(step) || step < 1 || step > 12)) {
1774
- console.error(chalk.red(`Error: Invalid step "${argv.step}". Must be 1-12.`));
1775
- process.exit(1);
1776
- }
1777
- if (step == null) {
1778
- // No step specified: setup or overview
2914
+ // Subcommand: codeyam editor steps show setup or cycle overview
2915
+ if (argv.step === 'steps') {
1779
2916
  if (!hasProject(root)) {
1780
2917
  printSetup(root);
1781
2918
  }
1782
2919
  else {
1783
2920
  const state = readState(root);
2921
+ // Clear prompt file when feature is done (step 16) so the hook
2922
+ // can capture the next feature request from the user.
2923
+ if (state?.step === 16) {
2924
+ clearEditorUserPrompt(root);
2925
+ }
1784
2926
  printCycleOverview(root, state);
1785
2927
  }
1786
2928
  return;
1787
2929
  }
2930
+ const step = argv.step ? parseInt(argv.step, 10) : undefined;
2931
+ if (step != null && (isNaN(step) || step < 1 || step > 16)) {
2932
+ console.error(chalk.red(`Error: Invalid step "${argv.step}". Must be 1-16.`));
2933
+ process.exit(1);
2934
+ }
2935
+ if (step == null) {
2936
+ // No step specified: launch editor server + open browser
2937
+ // Auto-init if needed
2938
+ let projectRoot = getStateProjectRoot();
2939
+ if (!projectRoot) {
2940
+ await initCommand.handler({
2941
+ force: false,
2942
+ autoInit: true,
2943
+ $0: '',
2944
+ _: [],
2945
+ });
2946
+ projectRoot = getStateProjectRoot();
2947
+ if (!projectRoot) {
2948
+ return;
2949
+ }
2950
+ }
2951
+ const configPath = path.join(projectRoot, '.codeyam', 'config.json');
2952
+ try {
2953
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
2954
+ const { projectSlug } = config;
2955
+ if (!projectSlug) {
2956
+ errorLog('Missing project slug. Try reinitializing with: codeyam init --force');
2957
+ return;
2958
+ }
2959
+ const connectionOk = await withoutSpinner(() => testEnvironment());
2960
+ if (!connectionOk) {
2961
+ errorLog('Environment validation failed');
2962
+ return;
2963
+ }
2964
+ const { project, branch } = await requireBranchAndProject(projectSlug);
2965
+ // Backfill _metadata into existing scenario files that predate the embedded metadata feature.
2966
+ // This reads metadata from the DB and writes it into files that don't have _metadata yet.
2967
+ try {
2968
+ const { getDatabase } = await import('../../../packages/database/index.js');
2969
+ const db = getDatabase();
2970
+ const dbScenarios = await db
2971
+ .selectFrom('editor_scenarios')
2972
+ .select([
2973
+ 'id',
2974
+ 'name',
2975
+ 'description',
2976
+ 'component_name',
2977
+ 'component_path',
2978
+ 'url',
2979
+ 'type',
2980
+ 'screenshot_path',
2981
+ 'viewport_width',
2982
+ 'viewport_height',
2983
+ 'created_at',
2984
+ 'updated_at',
2985
+ ])
2986
+ .where('project_id', '=', project.id)
2987
+ .execute();
2988
+ if (dbScenarios.length > 0) {
2989
+ const backfilled = backfillScenarioMetadata(projectRoot, dbScenarios);
2990
+ if (backfilled > 0) {
2991
+ console.log(chalk.green(` Backfilled metadata into ${backfilled} scenario file${backfilled > 1 ? 's' : ''}`));
2992
+ }
2993
+ }
2994
+ }
2995
+ catch {
2996
+ // Non-fatal — backfill is best-effort
2997
+ }
2998
+ // Auto-sync scenario files (with _metadata) to database
2999
+ const scenarioEntries = scanScenarioFiles(projectRoot);
3000
+ if (scenarioEntries.length > 0) {
3001
+ try {
3002
+ const { getDatabase } = await import('../../../packages/database/index.js');
3003
+ const db = getDatabase();
3004
+ const existingRows = await db
3005
+ .selectFrom('editor_scenarios')
3006
+ .select(['id', 'updated_at'])
3007
+ .where('project_id', '=', project.id)
3008
+ .execute();
3009
+ const syncResult = await syncScenarioFilesToDatabase(projectRoot, project.id, existingRows, async (row) => {
3010
+ await db
3011
+ .insertInto('editor_scenarios')
3012
+ .values(row)
3013
+ .execute();
3014
+ }, async (id, row) => {
3015
+ await db
3016
+ .updateTable('editor_scenarios')
3017
+ .set(row)
3018
+ .where('id', '=', id)
3019
+ .execute();
3020
+ });
3021
+ if (syncResult.inserted > 0 || syncResult.updated > 0) {
3022
+ const parts = [];
3023
+ if (syncResult.inserted > 0)
3024
+ parts.push(`${syncResult.inserted} imported`);
3025
+ if (syncResult.updated > 0)
3026
+ parts.push(`${syncResult.updated} updated`);
3027
+ console.log(chalk.green(` Synced scenarios from files: ${parts.join(', ')}`));
3028
+ }
3029
+ }
3030
+ catch {
3031
+ // Non-fatal — sync failure shouldn't block editor startup
3032
+ }
3033
+ }
3034
+ // `codeyam editor` (no step) always implies editor mode.
3035
+ // The empty-folder heuristic is no longer needed here — running this
3036
+ // command IS the signal. We still detect empty folders so that
3037
+ // the very first `codeyam editor` in a bare directory works before
3038
+ // metadata has been persisted.
3039
+ const editorMode = true;
3040
+ if (editorMode && !project.metadata?.labs?.simulations) {
3041
+ try {
3042
+ await updateProjectMetadata({
3043
+ projectSlug,
3044
+ metadataUpdate: {
3045
+ editorMode: true,
3046
+ labs: { simulations: true },
3047
+ },
3048
+ });
3049
+ const refreshed = await requireBranchAndProject(projectSlug);
3050
+ Object.assign(project, refreshed.project);
3051
+ }
3052
+ catch {
3053
+ // Non-fatal
3054
+ }
3055
+ }
3056
+ // Install skills/hooks
3057
+ const simulationsEnabled = project.metadata?.labs?.simulations ?? false;
3058
+ const skillMode = simulationsEnabled
3059
+ ? 'full'
3060
+ : editorMode
3061
+ ? 'editor'
3062
+ : 'memory';
3063
+ await installClaudeCodeSkills(projectRoot, {
3064
+ mode: skillMode,
3065
+ editorMode,
3066
+ });
3067
+ setupClaudeCodeSettings(projectRoot, {
3068
+ mode: skillMode,
3069
+ editorMode,
3070
+ });
3071
+ // Auto-finalize analyzer so codeyam analyze works
3072
+ if (editorMode) {
3073
+ const finalization = ensureAnalyzerFinalized();
3074
+ if (finalization.needed) {
3075
+ console.log(` Setting up simulations (${finalization.stepsRun.join(', ')})...`);
3076
+ }
3077
+ if (finalization.errors.length > 0) {
3078
+ for (const err of finalization.errors) {
3079
+ console.warn(` Warning: ${err.step} failed: ${err.message}`);
3080
+ }
3081
+ }
3082
+ }
3083
+ // Start background server (handles killing existing servers internally)
3084
+ const editorPort = argv.port || 3111;
3085
+ const { url } = await startBackgroundServer({
3086
+ port: editorPort,
3087
+ rootPath: projectRoot,
3088
+ project,
3089
+ branch,
3090
+ });
3091
+ // Build import graph on first startup if glossary exists but no entities yet
3092
+ const glossaryPath = path.join(projectRoot, '.codeyam', 'glossary.json');
3093
+ if (fs.existsSync(glossaryPath)) {
3094
+ const entities = await loadEntities({});
3095
+ if (!entities || entities.length === 0) {
3096
+ try {
3097
+ await handleAnalyzeImports({ silent: true });
3098
+ }
3099
+ catch {
3100
+ // Non-fatal
3101
+ }
3102
+ }
3103
+ }
3104
+ console.log();
3105
+ console.log(` Dashboard: ${url}`);
3106
+ console.log(' Run "codeyam --help" for all commands');
3107
+ console.log(chalk.bold(' Run "codeyam editor" to launch the editor at any time'));
3108
+ console.log();
3109
+ // Open browser to /editor
3110
+ try {
3111
+ const { execSync } = await import('child_process');
3112
+ const openCommand = process.platform === 'darwin'
3113
+ ? 'open'
3114
+ : process.platform === 'win32'
3115
+ ? 'start ""'
3116
+ : 'xdg-open';
3117
+ execSync(`${openCommand} "${url}/editor"`, { stdio: 'ignore' });
3118
+ }
3119
+ catch {
3120
+ // Silently fail if open command doesn't work
3121
+ }
3122
+ }
3123
+ catch (err) {
3124
+ errorLog('Failed to start CodeYam editor server');
3125
+ errorLog(err);
3126
+ process.exit(1);
3127
+ }
3128
+ return;
3129
+ }
1788
3130
  const state = readState(root);
3131
+ // Validate step transition — prevent skipping steps.
3132
+ // Exception: step 2 with --feature is always allowed because step 1's
3133
+ // instructions explicitly tell Claude to run `codeyam editor 2 --feature "..."`.
3134
+ // Step 1 is planning-only and may not persist state (no --feature flag).
3135
+ const skipValidation = step === 2 && argv.feature;
3136
+ if (!skipValidation) {
3137
+ const stepError = validateStepTransition(step, state?.step ?? null);
3138
+ if (stepError) {
3139
+ console.error(chalk.red(`Error: ${stepError}`));
3140
+ process.exit(1);
3141
+ }
3142
+ }
1789
3143
  switch (step) {
1790
3144
  case 1: {
1791
3145
  const feature = argv.feature || undefined;
1792
- printStep1(root, feature);
3146
+ const appFormats = argv['app-formats']
3147
+ ? argv['app-formats'].split(',').map((f) => f.trim())
3148
+ : undefined;
3149
+ const techStackId = argv['tech-stack'] || undefined;
3150
+ const prompt = argv.prompt || undefined;
3151
+ printStep1(root, feature, { appFormats, techStackId }, prompt);
1793
3152
  break;
1794
3153
  }
1795
3154
  case 2: {
@@ -1811,12 +3170,25 @@ const editorCommand = {
1811
3170
  case 9:
1812
3171
  case 10:
1813
3172
  case 11:
1814
- case 12: {
3173
+ case 12:
3174
+ case 13:
3175
+ case 14:
3176
+ case 15:
3177
+ case 16: {
1815
3178
  const feature = argv.feature || state?.feature;
1816
3179
  if (!feature) {
1817
3180
  console.error(chalk.red('Error: No feature in progress. Run codeyam editor 1 first.'));
1818
3181
  process.exit(1);
1819
3182
  }
3183
+ // Hard gate: steps 8+ require audit to have passed
3184
+ if (step >= 8) {
3185
+ const auditOk = await checkAuditGate();
3186
+ if (!auditOk) {
3187
+ console.error(chalk.red.bold('BLOCKED: The audit has not passed. Run `codeyam editor audit` and fix all issues before proceeding.'));
3188
+ console.error(chalk.yellow('Every function and hook must have a test file. Every component must have scenarios.'));
3189
+ process.exit(1);
3190
+ }
3191
+ }
1820
3192
  const stepFns = {
1821
3193
  3: printStep3,
1822
3194
  4: printStep4,
@@ -1828,6 +3200,10 @@ const editorCommand = {
1828
3200
  10: printStep10,
1829
3201
  11: printStep11,
1830
3202
  12: printStep12,
3203
+ 13: printStep13,
3204
+ 14: printStep14,
3205
+ 15: printStep15,
3206
+ 16: printStep16,
1831
3207
  };
1832
3208
  stepFns[step](root, feature);
1833
3209
  break;