@rien7/seji 0.0.0 → 0.6.0

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 (412) hide show
  1. package/bin/design-surface.mjs +6 -0
  2. package/bin/postinstall.mjs +19 -0
  3. package/bin/seji.mjs +573 -0
  4. package/dist/agent/host.d.mts +34 -0
  5. package/dist/agent/host.mjs +387 -0
  6. package/dist/agent/messages.d.mts +9 -0
  7. package/dist/agent/messages.mjs +70 -0
  8. package/dist/agent/runtimes.mjs +157 -0
  9. package/dist/cli/app.mjs +321 -0
  10. package/dist/cli/appScan.mjs +284 -0
  11. package/dist/cli/catalog.mjs +78 -0
  12. package/dist/cli/component.mjs +165 -0
  13. package/dist/cli/consolidate.mjs +159 -0
  14. package/dist/cli/cssImport.mjs +68 -0
  15. package/dist/cli/dev.mjs +335 -0
  16. package/dist/cli/doctor.mjs +306 -0
  17. package/dist/cli/init.mjs +338 -0
  18. package/dist/cli/legacyNames.mjs +266 -0
  19. package/dist/cli/migrate.mjs +163 -0
  20. package/dist/cli/prompt.mjs +34 -0
  21. package/dist/cli/propose.mjs +208 -0
  22. package/dist/cli/providers.mjs +344 -0
  23. package/dist/cli/reviewOps.mjs +110 -0
  24. package/dist/cli/semver.mjs +45 -0
  25. package/dist/cli/setup.mjs +357 -0
  26. package/dist/cli/sketches.mjs +47 -0
  27. package/dist/cli/skills.mjs +150 -0
  28. package/dist/cli/snapshot.mjs +107 -0
  29. package/dist/cli/tokenOps.mjs +120 -0
  30. package/dist/cli/types.mjs +191 -0
  31. package/dist/cli/updater.mjs +274 -0
  32. package/dist/components/astIndex.mjs +992 -0
  33. package/dist/components/ops.mjs +1069 -0
  34. package/dist/editor/AgentProposalCard.d.ts +10 -0
  35. package/dist/editor/AgentProposalCard.d.ts.map +1 -0
  36. package/dist/editor/AgentProposalCard.js +31 -0
  37. package/dist/editor/AgentProposalCard.js.map +1 -0
  38. package/dist/editor/App.d.ts +2 -0
  39. package/dist/editor/App.d.ts.map +1 -0
  40. package/dist/editor/App.js +2832 -0
  41. package/dist/editor/App.js.map +1 -0
  42. package/dist/editor/CanvasHud.d.ts +12 -0
  43. package/dist/editor/CanvasHud.d.ts.map +1 -0
  44. package/dist/editor/CanvasHud.js +13 -0
  45. package/dist/editor/CanvasHud.js.map +1 -0
  46. package/dist/editor/CanvasSurface.d.ts +31 -0
  47. package/dist/editor/CanvasSurface.d.ts.map +1 -0
  48. package/dist/editor/CanvasSurface.js +270 -0
  49. package/dist/editor/CanvasSurface.js.map +1 -0
  50. package/dist/editor/CommentPopover.d.ts +17 -0
  51. package/dist/editor/CommentPopover.d.ts.map +1 -0
  52. package/dist/editor/CommentPopover.js +62 -0
  53. package/dist/editor/CommentPopover.js.map +1 -0
  54. package/dist/editor/Comments.d.ts +13 -0
  55. package/dist/editor/Comments.d.ts.map +1 -0
  56. package/dist/editor/Comments.js +41 -0
  57. package/dist/editor/Comments.js.map +1 -0
  58. package/dist/editor/ComponentPage.d.ts +28 -0
  59. package/dist/editor/ComponentPage.d.ts.map +1 -0
  60. package/dist/editor/ComponentPage.js +55 -0
  61. package/dist/editor/ComponentPage.js.map +1 -0
  62. package/dist/editor/ComponentPanel.d.ts +38 -0
  63. package/dist/editor/ComponentPanel.d.ts.map +1 -0
  64. package/dist/editor/ComponentPanel.js +275 -0
  65. package/dist/editor/ComponentPanel.js.map +1 -0
  66. package/dist/editor/Glyph.d.ts +51 -0
  67. package/dist/editor/Glyph.d.ts.map +1 -0
  68. package/dist/editor/Glyph.js +50 -0
  69. package/dist/editor/Glyph.js.map +1 -0
  70. package/dist/editor/History.d.ts +7 -0
  71. package/dist/editor/History.d.ts.map +1 -0
  72. package/dist/editor/History.js +51 -0
  73. package/dist/editor/History.js.map +1 -0
  74. package/dist/editor/Inspector.d.ts +56 -0
  75. package/dist/editor/Inspector.d.ts.map +1 -0
  76. package/dist/editor/Inspector.js +510 -0
  77. package/dist/editor/Inspector.js.map +1 -0
  78. package/dist/editor/LazyMount.d.ts +10 -0
  79. package/dist/editor/LazyMount.d.ts.map +1 -0
  80. package/dist/editor/LazyMount.js +29 -0
  81. package/dist/editor/LazyMount.js.map +1 -0
  82. package/dist/editor/LocaleSwitch.d.ts +3 -0
  83. package/dist/editor/LocaleSwitch.d.ts.map +1 -0
  84. package/dist/editor/LocaleSwitch.js +9 -0
  85. package/dist/editor/LocaleSwitch.js.map +1 -0
  86. package/dist/editor/PreviewFrame.d.ts +10 -0
  87. package/dist/editor/PreviewFrame.d.ts.map +1 -0
  88. package/dist/editor/PreviewFrame.js +22 -0
  89. package/dist/editor/PreviewFrame.js.map +1 -0
  90. package/dist/editor/ProjectIndex.d.ts +12 -0
  91. package/dist/editor/ProjectIndex.d.ts.map +1 -0
  92. package/dist/editor/ProjectIndex.js +43 -0
  93. package/dist/editor/ProjectIndex.js.map +1 -0
  94. package/dist/editor/PromoteComponent.d.ts +28 -0
  95. package/dist/editor/PromoteComponent.d.ts.map +1 -0
  96. package/dist/editor/PromoteComponent.js +33 -0
  97. package/dist/editor/PromoteComponent.js.map +1 -0
  98. package/dist/editor/PromoteForm.d.ts +18 -0
  99. package/dist/editor/PromoteForm.d.ts.map +1 -0
  100. package/dist/editor/PromoteForm.js +35 -0
  101. package/dist/editor/PromoteForm.js.map +1 -0
  102. package/dist/editor/PromoteToken.d.ts +31 -0
  103. package/dist/editor/PromoteToken.d.ts.map +1 -0
  104. package/dist/editor/PromoteToken.js +94 -0
  105. package/dist/editor/PromoteToken.js.map +1 -0
  106. package/dist/editor/StatePreviews.d.ts +28 -0
  107. package/dist/editor/StatePreviews.d.ts.map +1 -0
  108. package/dist/editor/StatePreviews.js +113 -0
  109. package/dist/editor/StatePreviews.js.map +1 -0
  110. package/dist/editor/ValueCombo.d.ts +51 -0
  111. package/dist/editor/ValueCombo.d.ts.map +1 -0
  112. package/dist/editor/ValueCombo.js +260 -0
  113. package/dist/editor/ValueCombo.js.map +1 -0
  114. package/dist/editor/agent/AgentPanel.d.ts +19 -0
  115. package/dist/editor/agent/AgentPanel.d.ts.map +1 -0
  116. package/dist/editor/agent/AgentPanel.js +271 -0
  117. package/dist/editor/agent/AgentPanel.js.map +1 -0
  118. package/dist/editor/agent/Markdown.d.ts +5 -0
  119. package/dist/editor/agent/Markdown.d.ts.map +1 -0
  120. package/dist/editor/agent/Markdown.js +28 -0
  121. package/dist/editor/agent/Markdown.js.map +1 -0
  122. package/dist/editor/agent/agentApi.d.ts +106 -0
  123. package/dist/editor/agent/agentApi.d.ts.map +1 -0
  124. package/dist/editor/agent/agentApi.js +66 -0
  125. package/dist/editor/agent/agentApi.js.map +1 -0
  126. package/dist/editor/agent/toolLines.d.ts +38 -0
  127. package/dist/editor/agent/toolLines.d.ts.map +1 -0
  128. package/dist/editor/agent/toolLines.js +159 -0
  129. package/dist/editor/agent/toolLines.js.map +1 -0
  130. package/dist/editor/agent/useAgent.d.ts +15 -0
  131. package/dist/editor/agent/useAgent.d.ts.map +1 -0
  132. package/dist/editor/agent/useAgent.js +65 -0
  133. package/dist/editor/agent/useAgent.js.map +1 -0
  134. package/dist/editor/api.d.ts +378 -0
  135. package/dist/editor/api.d.ts.map +1 -0
  136. package/dist/editor/api.js +247 -0
  137. package/dist/editor/api.js.map +1 -0
  138. package/dist/editor/camera.d.ts +18 -0
  139. package/dist/editor/camera.d.ts.map +1 -0
  140. package/dist/editor/camera.js +40 -0
  141. package/dist/editor/camera.js.map +1 -0
  142. package/dist/editor/canvas.d.ts +25 -0
  143. package/dist/editor/canvas.d.ts.map +1 -0
  144. package/dist/editor/canvas.js +35 -0
  145. package/dist/editor/canvas.js.map +1 -0
  146. package/dist/editor/changes/ChangesPage.d.ts +25 -0
  147. package/dist/editor/changes/ChangesPage.d.ts.map +1 -0
  148. package/dist/editor/changes/ChangesPage.js +132 -0
  149. package/dist/editor/changes/ChangesPage.js.map +1 -0
  150. package/dist/editor/changes/changeModel.d.ts +25 -0
  151. package/dist/editor/changes/changeModel.d.ts.map +1 -0
  152. package/dist/editor/changes/changeModel.js +81 -0
  153. package/dist/editor/changes/changeModel.js.map +1 -0
  154. package/dist/editor/changes/changeState.d.mts +29 -0
  155. package/dist/editor/changes/changeState.mjs +187 -0
  156. package/dist/editor/chrome/EditorChrome.d.ts +49 -0
  157. package/dist/editor/chrome/EditorChrome.d.ts.map +1 -0
  158. package/dist/editor/chrome/EditorChrome.js +21 -0
  159. package/dist/editor/chrome/EditorChrome.js.map +1 -0
  160. package/dist/editor/drafts.d.ts +46 -0
  161. package/dist/editor/drafts.d.ts.map +1 -0
  162. package/dist/editor/drafts.js +38 -0
  163. package/dist/editor/drafts.js.map +1 -0
  164. package/dist/editor/i18n.d.ts +29 -0
  165. package/dist/editor/i18n.d.ts.map +1 -0
  166. package/dist/editor/i18n.js +2320 -0
  167. package/dist/editor/i18n.js.map +1 -0
  168. package/dist/editor/iconStroke.d.ts +6 -0
  169. package/dist/editor/iconStroke.d.ts.map +1 -0
  170. package/dist/editor/iconStroke.js +6 -0
  171. package/dist/editor/iconStroke.js.map +1 -0
  172. package/dist/editor/main.d.ts +2 -0
  173. package/dist/editor/main.d.ts.map +1 -0
  174. package/dist/editor/main.js +14 -0
  175. package/dist/editor/main.js.map +1 -0
  176. package/dist/editor/model.d.ts +16 -0
  177. package/dist/editor/model.d.ts.map +1 -0
  178. package/dist/editor/model.js +11 -0
  179. package/dist/editor/model.js.map +1 -0
  180. package/dist/editor/reasons.d.ts +44 -0
  181. package/dist/editor/reasons.d.ts.map +1 -0
  182. package/dist/editor/reasons.js +131 -0
  183. package/dist/editor/reasons.js.map +1 -0
  184. package/dist/editor/reviewLifecycle.d.ts +8 -0
  185. package/dist/editor/reviewLifecycle.d.ts.map +1 -0
  186. package/dist/editor/reviewLifecycle.js +21 -0
  187. package/dist/editor/reviewLifecycle.js.map +1 -0
  188. package/dist/editor/styles.css +8737 -0
  189. package/dist/editor/tokenMatch.d.ts +59 -0
  190. package/dist/editor/tokenMatch.d.ts.map +1 -0
  191. package/dist/editor/tokenMatch.js +198 -0
  192. package/dist/editor/tokenMatch.js.map +1 -0
  193. package/dist/editor/tokens/ConsolidatePage.d.ts +16 -0
  194. package/dist/editor/tokens/ConsolidatePage.d.ts.map +1 -0
  195. package/dist/editor/tokens/ConsolidatePage.js +244 -0
  196. package/dist/editor/tokens/ConsolidatePage.js.map +1 -0
  197. package/dist/editor/tokens/TokenActivity.d.ts +18 -0
  198. package/dist/editor/tokens/TokenActivity.d.ts.map +1 -0
  199. package/dist/editor/tokens/TokenActivity.js +18 -0
  200. package/dist/editor/tokens/TokenActivity.js.map +1 -0
  201. package/dist/editor/tokens/TokenDialogs.d.ts +26 -0
  202. package/dist/editor/tokens/TokenDialogs.d.ts.map +1 -0
  203. package/dist/editor/tokens/TokenDialogs.js +119 -0
  204. package/dist/editor/tokens/TokenDialogs.js.map +1 -0
  205. package/dist/editor/tokens/TokenList.d.ts +21 -0
  206. package/dist/editor/tokens/TokenList.d.ts.map +1 -0
  207. package/dist/editor/tokens/TokenList.js +98 -0
  208. package/dist/editor/tokens/TokenList.js.map +1 -0
  209. package/dist/editor/tokens/TokenPage.d.ts +25 -0
  210. package/dist/editor/tokens/TokenPage.d.ts.map +1 -0
  211. package/dist/editor/tokens/TokenPage.js +108 -0
  212. package/dist/editor/tokens/TokenPage.js.map +1 -0
  213. package/dist/editor/tokens/tokenModel.d.ts +35 -0
  214. package/dist/editor/tokens/tokenModel.d.ts.map +1 -0
  215. package/dist/editor/tokens/tokenModel.js +72 -0
  216. package/dist/editor/tokens/tokenModel.js.map +1 -0
  217. package/dist/editor/ui/Button.d.ts +3 -0
  218. package/dist/editor/ui/Button.d.ts.map +1 -0
  219. package/dist/editor/ui/Button.js +6 -0
  220. package/dist/editor/ui/Button.js.map +1 -0
  221. package/dist/editor/ui/CommentBox.d.ts +23 -0
  222. package/dist/editor/ui/CommentBox.d.ts.map +1 -0
  223. package/dist/editor/ui/CommentBox.js +41 -0
  224. package/dist/editor/ui/CommentBox.js.map +1 -0
  225. package/dist/editor/ui/Icon.d.ts +8 -0
  226. package/dist/editor/ui/Icon.d.ts.map +1 -0
  227. package/dist/editor/ui/Icon.js +6 -0
  228. package/dist/editor/ui/Icon.js.map +1 -0
  229. package/dist/editor/ui/IconButton.d.ts +11 -0
  230. package/dist/editor/ui/IconButton.d.ts.map +1 -0
  231. package/dist/editor/ui/IconButton.js +6 -0
  232. package/dist/editor/ui/IconButton.js.map +1 -0
  233. package/dist/editor/ui/NumberInput.d.ts +14 -0
  234. package/dist/editor/ui/NumberInput.d.ts.map +1 -0
  235. package/dist/editor/ui/NumberInput.js +6 -0
  236. package/dist/editor/ui/NumberInput.js.map +1 -0
  237. package/dist/editor/ui/PageLine.d.ts +14 -0
  238. package/dist/editor/ui/PageLine.d.ts.map +1 -0
  239. package/dist/editor/ui/PageLine.js +7 -0
  240. package/dist/editor/ui/PageLine.js.map +1 -0
  241. package/dist/editor/ui/SearchPicker.d.ts +41 -0
  242. package/dist/editor/ui/SearchPicker.d.ts.map +1 -0
  243. package/dist/editor/ui/SearchPicker.js +82 -0
  244. package/dist/editor/ui/SearchPicker.js.map +1 -0
  245. package/dist/editor/ui/Select.d.ts +19 -0
  246. package/dist/editor/ui/Select.d.ts.map +1 -0
  247. package/dist/editor/ui/Select.js +12 -0
  248. package/dist/editor/ui/Select.js.map +1 -0
  249. package/dist/editor/ui/TokenField.d.ts +14 -0
  250. package/dist/editor/ui/TokenField.d.ts.map +1 -0
  251. package/dist/editor/ui/TokenField.js +41 -0
  252. package/dist/editor/ui/TokenField.js.map +1 -0
  253. package/dist/editor/ui/TokenPicker.d.ts +31 -0
  254. package/dist/editor/ui/TokenPicker.d.ts.map +1 -0
  255. package/dist/editor/ui/TokenPicker.js +26 -0
  256. package/dist/editor/ui/TokenPicker.js.map +1 -0
  257. package/dist/editor/useBuildError.d.ts +7 -0
  258. package/dist/editor/useBuildError.d.ts.map +1 -0
  259. package/dist/editor/useBuildError.js +30 -0
  260. package/dist/editor/useBuildError.js.map +1 -0
  261. package/dist/editor/useLatestRequest.d.ts +22 -0
  262. package/dist/editor/useLatestRequest.d.ts.map +1 -0
  263. package/dist/editor/useLatestRequest.js +49 -0
  264. package/dist/editor/useLatestRequest.js.map +1 -0
  265. package/dist/editor-bundle/editor.css +2 -0
  266. package/dist/editor-bundle/editor.js +83 -0
  267. package/dist/editor-ui.d.ts +15 -0
  268. package/dist/editor-ui.d.ts.map +1 -0
  269. package/dist/editor-ui.js +14 -0
  270. package/dist/editor-ui.js.map +1 -0
  271. package/dist/inspector/runtime.d.ts +18 -0
  272. package/dist/inspector/runtime.d.ts.map +1 -0
  273. package/dist/inspector/runtime.js +1280 -0
  274. package/dist/inspector/runtime.js.map +1 -0
  275. package/dist/preview/main.d.ts +3 -0
  276. package/dist/preview/main.d.ts.map +1 -0
  277. package/dist/preview/main.js +320 -0
  278. package/dist/preview/main.js.map +1 -0
  279. package/dist/preview/preview.css +40 -0
  280. package/dist/runtime/index.d.ts +3 -0
  281. package/dist/runtime/index.d.ts.map +1 -0
  282. package/dist/runtime/index.js +2 -0
  283. package/dist/runtime/index.js.map +1 -0
  284. package/dist/shared/buildError.d.mts +27 -0
  285. package/dist/shared/buildError.mjs +141 -0
  286. package/dist/shared/cameraFit.d.mts +16 -0
  287. package/dist/shared/cameraFit.mjs +47 -0
  288. package/dist/shared/canvasLayout.d.mts +13 -0
  289. package/dist/shared/canvasLayout.mjs +171 -0
  290. package/dist/shared/commentShots.d.mts +12 -0
  291. package/dist/shared/commentShots.mjs +53 -0
  292. package/dist/shared/componentExtract.d.mts +43 -0
  293. package/dist/shared/componentExtract.mjs +136 -0
  294. package/dist/shared/componentMeta.d.mts +26 -0
  295. package/dist/shared/componentMeta.mjs +87 -0
  296. package/dist/shared/componentOps.d.mts +70 -0
  297. package/dist/shared/componentOps.mjs +407 -0
  298. package/dist/shared/componentTarget.d.mts +15 -0
  299. package/dist/shared/componentTarget.mjs +58 -0
  300. package/dist/shared/components.d.mts +30 -0
  301. package/dist/shared/components.mjs +106 -0
  302. package/dist/shared/consolidateCategories.d.mts +2 -0
  303. package/dist/shared/consolidateCategories.mjs +6 -0
  304. package/dist/shared/env.d.mts +4 -0
  305. package/dist/shared/env.mjs +18 -0
  306. package/dist/shared/gitChanges.d.mts +2 -0
  307. package/dist/shared/gitChanges.mjs +30 -0
  308. package/dist/shared/oklab.d.mts +6 -0
  309. package/dist/shared/oklab.mjs +56 -0
  310. package/dist/shared/optimizeEntries.d.mts +5 -0
  311. package/dist/shared/optimizeEntries.mjs +24 -0
  312. package/dist/shared/packages.d.mts +11 -0
  313. package/dist/shared/packages.mjs +96 -0
  314. package/dist/shared/projectFiles.d.mts +23 -0
  315. package/dist/shared/projectFiles.mjs +72 -0
  316. package/dist/shared/prompt.d.mts +20 -0
  317. package/dist/shared/prompt.mjs +201 -0
  318. package/dist/shared/proposals.d.mts +11 -0
  319. package/dist/shared/proposals.mjs +42 -0
  320. package/dist/shared/protocol.d.ts +122 -0
  321. package/dist/shared/protocol.d.ts.map +1 -0
  322. package/dist/shared/protocol.js +7 -0
  323. package/dist/shared/protocol.js.map +1 -0
  324. package/dist/shared/reviewArchive.d.mts +4 -0
  325. package/dist/shared/reviewArchive.mjs +19 -0
  326. package/dist/shared/reviewStore.d.mts +30 -0
  327. package/dist/shared/reviewStore.mjs +218 -0
  328. package/dist/shared/reviewVerify.d.mts +21 -0
  329. package/dist/shared/reviewVerify.mjs +158 -0
  330. package/dist/shared/sizeModes.d.mts +15 -0
  331. package/dist/shared/sizeModes.mjs +53 -0
  332. package/dist/shared/sketches.d.mts +10 -0
  333. package/dist/shared/sketches.mjs +64 -0
  334. package/dist/shared/snapshotCheck.d.mts +13 -0
  335. package/dist/shared/snapshotCheck.mjs +81 -0
  336. package/dist/shared/timeout.d.mts +1 -0
  337. package/dist/shared/timeout.mjs +15 -0
  338. package/dist/shared/tokens.d.ts +2 -0
  339. package/dist/shared/tokens.d.ts.map +1 -0
  340. package/dist/shared/tokens.js +2 -0
  341. package/dist/shared/tokens.js.map +1 -0
  342. package/dist/shared/types.d.ts +689 -0
  343. package/dist/shared/types.d.ts.map +1 -0
  344. package/dist/shared/types.js +13 -0
  345. package/dist/shared/types.js.map +1 -0
  346. package/dist/shared/wheelRouting.d.mts +9 -0
  347. package/dist/shared/wheelRouting.mjs +31 -0
  348. package/dist/shared/writeScope.mjs +96 -0
  349. package/dist/snapshots/diff.d.mts +28 -0
  350. package/dist/snapshots/diff.mjs +263 -0
  351. package/dist/snapshots/index.d.mts +110 -0
  352. package/dist/snapshots/index.mjs +638 -0
  353. package/dist/snapshots/render.d.mts +24 -0
  354. package/dist/snapshots/render.mjs +250 -0
  355. package/dist/snapshots/toolOps.d.mts +25 -0
  356. package/dist/snapshots/toolOps.mjs +69 -0
  357. package/dist/tokens/adapters/css.mjs +51 -0
  358. package/dist/tokens/adapters/cssInCode.mjs +314 -0
  359. package/dist/tokens/adapters/oxcShared.mjs +80 -0
  360. package/dist/tokens/adapters/preprocessor.mjs +63 -0
  361. package/dist/tokens/adapters/registry.mjs +53 -0
  362. package/dist/tokens/adapters/tailwindcss.mjs +424 -0
  363. package/dist/tokens/adapters/types.mjs +117 -0
  364. package/dist/tokens/consolidate/index.d.mts +42 -0
  365. package/dist/tokens/consolidate/index.mjs +111 -0
  366. package/dist/tokens/consolidate/normalize.mjs +479 -0
  367. package/dist/tokens/consolidate/plan.mjs +726 -0
  368. package/dist/tokens/consolidate/scan.mjs +928 -0
  369. package/dist/tokens/extract.mjs +441 -0
  370. package/dist/tokens/moduleData.d.mts +14 -0
  371. package/dist/tokens/moduleData.mjs +32 -0
  372. package/dist/tokens/opLock.d.mts +4 -0
  373. package/dist/tokens/opLock.mjs +108 -0
  374. package/dist/tokens/ops.d.mts +71 -0
  375. package/dist/tokens/ops.mjs +1511 -0
  376. package/dist/tokens/pipeline.mjs +813 -0
  377. package/dist/tokens/report.d.mts +47 -0
  378. package/dist/tokens/report.mjs +257 -0
  379. package/dist/tokens/rewrite/code.mjs +172 -0
  380. package/dist/tokens/rewrite/css.mjs +154 -0
  381. package/dist/tokens/rewrite/index.mjs +244 -0
  382. package/dist/tokens/rewrite/tailwind.mjs +288 -0
  383. package/dist/tokens/rewrite/text.mjs +116 -0
  384. package/dist/tokens/rewrite/value.mjs +115 -0
  385. package/dist/tokens/usage.d.mts +97 -0
  386. package/dist/tokens/usage.mjs +680 -0
  387. package/dist/vite/agent.d.ts +21 -0
  388. package/dist/vite/agent.d.ts.map +1 -0
  389. package/dist/vite/agent.js +165 -0
  390. package/dist/vite/agent.js.map +1 -0
  391. package/dist/vite/events.d.ts +27 -0
  392. package/dist/vite/events.d.ts.map +1 -0
  393. package/dist/vite/events.js +156 -0
  394. package/dist/vite/events.js.map +1 -0
  395. package/dist/vite/layout.d.ts +2 -0
  396. package/dist/vite/layout.d.ts.map +1 -0
  397. package/dist/vite/layout.js +4 -0
  398. package/dist/vite/layout.js.map +1 -0
  399. package/dist/vite/plugin.d.ts +40 -0
  400. package/dist/vite/plugin.d.ts.map +1 -0
  401. package/dist/vite/plugin.js +1255 -0
  402. package/dist/vite/plugin.js.map +1 -0
  403. package/dist/vite/requestGuard.d.mts +3 -0
  404. package/dist/vite/requestGuard.mjs +43 -0
  405. package/dist/vite/review.d.ts +11 -0
  406. package/dist/vite/review.d.ts.map +1 -0
  407. package/dist/vite/review.js +283 -0
  408. package/dist/vite/review.js.map +1 -0
  409. package/package.json +106 -1
  410. package/skills/seji/SKILL.md +395 -0
  411. package/skills/seji-authoring/SKILL.md +397 -0
  412. package/skills/seji-tokens/SKILL.md +432 -0
@@ -0,0 +1,1069 @@
1
+ // Component operations the tool executes itself, without the agent: rename a component,
2
+ // merge one into another, and move a deprecated component's usages to its replacement
3
+ // (`deprecate --replace-all`). Every place comes from the syntax-tree index
4
+ // (src/components/astIndex.mjs), never from file text:
5
+ // - the declaration, its export specifiers, import specifiers (an aliased import keeps its
6
+ // local name: only the imported side changes), re-exports in barrels, namespace members
7
+ // (`UI.Button`, `<UI.Button>`), JSX open / close tags, `as={Button}`,
8
+ // `createElement(Button)`, `typeof Button`, shorthand properties;
9
+ // - the design/components.ts registration key and the design/components.json entry;
10
+ // - for a rename, the file named after the component (`Button.tsx` → `ChromeButton.tsx`)
11
+ // and every module specifier that imports it.
12
+ // What cannot be rewritten safely is left for the agent with file:line and a reason: string
13
+ // literals, object keys, dynamic imports, namespace objects, package specifiers, and files
14
+ // outside the write scope (shared/writeScope.mjs, the same as token operations: the project
15
+ // root plus any `writableDirs`; when the component itself is declared outside it nothing is
16
+ // written at all).
17
+ //
18
+ // Like token operations: `dryRun` lists every place; a real run holds the project's
19
+ // operation lock, checks each file still has the content that was planned, writes all files
20
+ // or none, rebuilds the token manifest (it lists files), and records ONE review item + batch
21
+ // in design/<design>/review.json with undo edits and file moves, so `component revert
22
+ // <batch>` restores everything.
23
+ import { randomUUID } from 'node:crypto'
24
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync } from 'node:fs'
25
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
26
+
27
+ import { COMPONENT_META_FILE, componentMetaPath } from '../shared/componentMeta.mjs'
28
+ import { SAFE_DESIGN_ID, mutateReview, readReviewFile, reviewFilePath } from '../shared/reviewStore.mjs'
29
+ import { writeScope } from '../shared/writeScope.mjs'
30
+ import { TokenLockTimeoutError, withTokenOpLock } from '../tokens/opLock.mjs'
31
+ import { loadTokenConfig, runTokenPipeline } from '../tokens/pipeline.mjs'
32
+ import { StaleFileError, undoEdits, undoForChanges, writeFileAtomic } from '../tokens/rewrite/index.mjs'
33
+ import { applyEdits, sha256 } from '../tokens/rewrite/text.mjs'
34
+ import { buildUsageIndex, readComponentRegistrations } from '../tokens/usage.mjs'
35
+ import { analyzeSource } from './astIndex.mjs'
36
+
37
+ export const COMPONENT_OPS = ['rename', 'merge', 'replace']
38
+
39
+ const MAX_ATTEMPTS = 3
40
+ const MAX_ITEM_CHANGES = 200
41
+ const COMPONENT_NAME = /^[A-Z][A-Za-z0-9_]*$/
42
+ const REWRITABLE_SPECIFIER = /^(?:\.{1,2}\/|\/|@\/|~\/|#)/
43
+
44
+ const toPosix = (file) => file.split(sep).join('/')
45
+ const isObject = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value)
46
+ const realOf = (file) => {
47
+ try {
48
+ return realpathSync(file)
49
+ } catch {
50
+ return file
51
+ }
52
+ }
53
+ const readOrNull = (abs) => {
54
+ try {
55
+ return readFileSync(abs, 'utf8')
56
+ } catch (error) {
57
+ if (error?.code === 'ENOENT') return null
58
+ throw error
59
+ }
60
+ }
61
+
62
+ export class ComponentOpError extends Error {
63
+ constructor(message, details) {
64
+ super(message)
65
+ this.name = 'ComponentOpError'
66
+ if (details) {
67
+ this.details = details
68
+ if (details.code) this.code = details.code
69
+ }
70
+ }
71
+ }
72
+
73
+ const fail = (message, details) => {
74
+ throw new ComponentOpError(message, details)
75
+ }
76
+
77
+ async function locked(root, fn) {
78
+ try {
79
+ return await withTokenOpLock(root, fn)
80
+ } catch (error) {
81
+ if (error instanceof TokenLockTimeoutError) fail(error.message, { code: 'busy' })
82
+ throw error
83
+ }
84
+ }
85
+
86
+ // ---------------------------------------------------------------------------------------
87
+ // Planning
88
+
89
+ function createPlan(ctx, { op, from, to, into }) {
90
+ const files = new Map()
91
+ const fileOf = (abs) => {
92
+ let entry = files.get(abs)
93
+ if (!entry) {
94
+ const info = ctx.index.infos.get(abs)
95
+ entry = {
96
+ abs,
97
+ file: ctx.index.relOf.get(abs) ?? toPosix(relative(ctx.root, abs)),
98
+ info,
99
+ content: info.content,
100
+ edits: [],
101
+ leftovers: [],
102
+ }
103
+ files.set(abs, entry)
104
+ }
105
+ return entry
106
+ }
107
+ return { op, from, to, into, files, fileOf, moves: [], notes: [], meta: null }
108
+ }
109
+
110
+ /** Replace the identifier `name` starting at `start` (checked against the source). */
111
+ function renameAt(entry, start, name, text, kind) {
112
+ if (entry.content.slice(start, start + name.length) !== name) {
113
+ entry.leftovers.push({ offset: start, reason: 'unexpected-source', text: name })
114
+ return null
115
+ }
116
+ const edit = { start, end: start + name.length, text, kind, from: name }
117
+ entry.edits.push(edit)
118
+ return edit
119
+ }
120
+
121
+ const taken = (info, name) => info.declarations.has(name) || info.imports.has(name)
122
+
123
+ /** New specifier for a module that moved from `<stem>` to `<to>`, or null when it cannot be rewritten. */
124
+ function respecifier(spec, stem, to) {
125
+ if (!REWRITABLE_SPECIFIER.test(spec)) return null
126
+ const slash = spec.lastIndexOf('/')
127
+ const last = spec.slice(slash + 1)
128
+ const ext = /\.[cm]?[jt]sx?$/.exec(last)?.[0] ?? ''
129
+ if (last.slice(0, last.length - ext.length) !== stem) return null
130
+ return `${spec.slice(0, slash + 1)}${to}${ext}`
131
+ }
132
+
133
+ /** Leftovers every operation reports: string literals / object keys named like the component, dynamic imports. */
134
+ function collectLeftovers(ctx, plan, definition, skip) {
135
+ const name = definition.name
136
+ for (const [abs, info] of ctx.index.infos) {
137
+ for (const literal of info.strings) {
138
+ if (literal.value !== name || skip.has(`${abs}:${literal.start}`)) continue
139
+ plan.fileOf(abs).leftovers.push({ offset: literal.start, reason: 'string', text: `'${name}'` })
140
+ }
141
+ for (const key of info.objectKeys) {
142
+ if (key.name !== name || skip.has(`${abs}:${key.start}`)) continue
143
+ plan.fileOf(abs).leftovers.push({ offset: key.start, reason: 'object-key', text: name })
144
+ }
145
+ }
146
+ for (const reference of ctx.index.referencesOf(definition)) {
147
+ if (!reference.dynamic) continue
148
+ plan.fileOf(reference.abs).leftovers.push({ offset: reference.ref.start, reason: 'dynamic-import', text: name })
149
+ }
150
+ }
151
+
152
+ /** Rename: every reference that resolves to the declaration, the registration, the file. */
153
+ function planRename(ctx, plan) {
154
+ const { index } = ctx
155
+ const definition = plan.from
156
+ const name = definition.name
157
+ const to = plan.to
158
+ const same = (target) => index.sameDefinition(target, definition)
159
+ const declaring = index.infos.get(definition.abs)
160
+
161
+ /** Does module `abs` export the component under `exportName`, and does that name change? */
162
+ const exportRenamed = (abs, exportName, seen = new Set()) => {
163
+ if (!abs || !exportName || exportName === 'default') return false
164
+ const key = `${abs}\0${exportName}`
165
+ if (seen.has(key)) return false
166
+ seen.add(key)
167
+ const info = index.infos.get(abs)
168
+ if (!info || !same(index.resolveExport(abs, exportName))) return false
169
+ const entry = info.exports.get(exportName)
170
+ if (entry?.kind === 'local') {
171
+ if (abs === definition.abs && entry.local && info.declarations.has(entry.local)) return exportName === definition.exportName
172
+ if (entry.aliased) return false
173
+ return localRenamed(abs, entry.local, seen)
174
+ }
175
+ if (entry?.kind === 'reexport') return !entry.aliased && exportRenamed(index.targetOf(abs, entry.source), entry.imported, seen)
176
+ if (entry) return false
177
+ for (const star of info.stars) {
178
+ const target = index.targetOf(abs, star.source)
179
+ if (target && same(index.resolveExport(target, exportName))) return exportRenamed(target, exportName, seen)
180
+ }
181
+ return false
182
+ }
183
+ /** Does the local binding `local` in `abs` (the declaration or an import of it) get the new name? */
184
+ const localRenamed = (abs, local, seen = new Set()) => {
185
+ if (!local) return false
186
+ const info = index.infos.get(abs)
187
+ if (!info) return false
188
+ if (abs === definition.abs && local === definition.local) {
189
+ return definition.exportName === local || definition.exportName === 'default'
190
+ }
191
+ const binding = info.imports.get(local)
192
+ if (!binding || binding.imported === '*' || !same(index.resolveLocal(abs, local))) return false
193
+ if (taken(info, to)) return false
194
+ if (binding.imported === 'default') return local === name
195
+ return !binding.aliased && exportRenamed(index.targetOf(abs, binding.source), binding.imported, seen)
196
+ }
197
+
198
+ if (definition.local && localRenamed(definition.abs, definition.local) && taken(declaring, to)) {
199
+ fail(`${plan.fileOf(definition.abs).file} already declares or imports ${to}`, { code: 'name-conflict', name: to })
200
+ }
201
+
202
+ const skip = new Set()
203
+ for (const [abs, info] of index.infos) {
204
+ const renamed = new Set()
205
+ let entry = null
206
+ const fileEntry = () => (entry ??= plan.fileOf(abs))
207
+ if (abs === definition.abs) {
208
+ if (definition.local && localRenamed(abs, definition.local)) {
209
+ renamed.add(definition.local)
210
+ renameAt(fileEntry(), info.declarations.get(definition.local).id.start, definition.local, to, 'declaration')
211
+ } else if (definition.exportName !== 'default') {
212
+ const exported = info.exports.get(definition.exportName)?.spec?.exported
213
+ if (exported) renameAt(fileEntry(), exported.start, definition.exportName, to, 'export')
214
+ }
215
+ }
216
+ for (const [local, binding] of info.imports) {
217
+ if (binding.imported === '*' || !same(index.resolveLocal(abs, local))) continue
218
+ if (binding.imported === 'default') {
219
+ if (localRenamed(abs, local)) {
220
+ renamed.add(local)
221
+ renameAt(fileEntry(), binding.spec.local.start, local, to, 'import')
222
+ }
223
+ continue
224
+ }
225
+ if (!exportRenamed(index.targetOf(abs, binding.source), binding.imported)) continue
226
+ const imported = binding.spec.imported
227
+ if (imported?.type !== 'Identifier') {
228
+ fileEntry().leftovers.push({ offset: binding.spec.start, reason: 'string-specifier', text: binding.imported })
229
+ } else if (binding.aliased) {
230
+ renameAt(fileEntry(), imported.start, binding.imported, to, 'import')
231
+ } else if (localRenamed(abs, local)) {
232
+ renamed.add(local)
233
+ renameAt(fileEntry(), imported.start, local, to, 'import')
234
+ } else {
235
+ // The new name is taken here: keep the local name (`import { ChromeButton as Button }`).
236
+ renameAt(fileEntry(), imported.start, local, `${to} as ${local}`, 'import')
237
+ }
238
+ }
239
+ for (const [, exported] of info.exports) {
240
+ if (exported.kind !== 'reexport') continue
241
+ if (!exportRenamed(index.targetOf(abs, exported.source), exported.imported)) continue
242
+ const local = exported.spec?.local
243
+ if (local?.type !== 'Identifier') {
244
+ fileEntry().leftovers.push({ offset: exported.statement.start, reason: 'string-specifier', text: exported.imported })
245
+ continue
246
+ }
247
+ renameAt(fileEntry(), local.start, exported.imported, to, 'reexport')
248
+ }
249
+ for (const ref of info.refs) {
250
+ const binding = info.imports.get(ref.name)
251
+ if (binding?.imported === '*') {
252
+ const target = index.targetOf(abs, binding.source)
253
+ if (!target) continue
254
+ if (ref.member) {
255
+ if (!exportRenamed(target, ref.member.name)) continue
256
+ if (ref.member.computed) {
257
+ const quote = info.content[ref.member.start]
258
+ fileEntry().edits.push({ start: ref.member.start, end: ref.member.end, text: `${quote}${to}${quote}`, kind: 'member', from: ref.member.name })
259
+ } else {
260
+ renameAt(fileEntry(), ref.member.start, ref.member.name, to, 'member')
261
+ }
262
+ } else if (exportRenamed(target, name)) {
263
+ fileEntry().leftovers.push({ offset: ref.start, reason: 'namespace-object', text: ref.name })
264
+ }
265
+ continue
266
+ }
267
+ if (!renamed.has(ref.name) || !same(index.resolveRef(abs, ref))) continue
268
+ if (ref.kind === 'shorthand') {
269
+ fileEntry().edits.push({ start: ref.start, end: ref.end, text: `${ref.name}: ${to}`, kind: 'ref', from: ref.name, ref: true })
270
+ } else {
271
+ const edit = renameAt(fileEntry(), ref.start, ref.name, to, ref.kind === 'jsx-close' ? 'jsx' : ref.kind)
272
+ if (edit) edit.ref = true
273
+ }
274
+ }
275
+ }
276
+
277
+ // design/components.ts: the registration key.
278
+ const registrations = readComponentRegistrations(ctx.root)
279
+ if (registrations.pages.has(to)) fail(`design/components.ts already registers ${to}`, { code: 'name-taken', name: to })
280
+ const registration = registrations.pages.get(name)
281
+ if (registration && registrations.file) {
282
+ const abs = realOf(registrations.file)
283
+ if (index.infos.has(abs)) {
284
+ const entry = plan.fileOf(abs)
285
+ const { start, end, quoted } = registration.key
286
+ const quote = quoted ? entry.content[start] : ''
287
+ entry.edits.push({ start, end, text: `${quote}${to}${quote}`, kind: 'registration', from: entry.content.slice(start, end) })
288
+ skip.add(`${abs}:${start}`)
289
+ }
290
+ }
291
+
292
+ // The file named after the component moves with it (same directory).
293
+ const declaringFile = plan.fileOf(definition.abs).file
294
+ const stem = basename(definition.abs, extname(definition.abs))
295
+ if (stem === name) {
296
+ const siblings = index.exportedComponentsOf(definition.abs).filter((item) => !same(item))
297
+ const nextAbs = join(dirname(definition.abs), `${to}${extname(definition.abs)}`)
298
+ const nextFile = toPosix(join(dirname(declaringFile), basename(nextAbs)))
299
+ if (siblings.length) {
300
+ plan.notes.push(`${declaringFile} also exports ${siblings.map((item) => item.name).join(', ')}; it keeps its file name`)
301
+ } else if (existsSync(nextAbs)) {
302
+ plan.notes.push(`${nextFile} already exists; ${declaringFile} keeps its file name`)
303
+ } else {
304
+ plan.moves.push({ fromAbs: definition.abs, toAbs: nextAbs, from: declaringFile, to: nextFile })
305
+ for (const [abs, info] of index.infos) {
306
+ for (const moduleRef of info.moduleRefs) {
307
+ if (index.targetOf(abs, moduleRef.source) !== definition.abs) continue
308
+ const entry = plan.fileOf(abs)
309
+ const next = respecifier(moduleRef.source, stem, to)
310
+ if (next === null) {
311
+ entry.leftovers.push({ offset: moduleRef.start, reason: 'module-specifier', text: moduleRef.source })
312
+ continue
313
+ }
314
+ const quote = info.content[moduleRef.start]
315
+ entry.edits.push({
316
+ start: moduleRef.start,
317
+ end: moduleRef.end,
318
+ text: `${quote}${next}${quote}`,
319
+ kind: 'specifier',
320
+ from: info.content.slice(moduleRef.start, moduleRef.end),
321
+ })
322
+ }
323
+ }
324
+ }
325
+ }
326
+
327
+ // design/components.json: the entry moves to the new name; replacements follow.
328
+ plan.meta = metaDraft(ctx.root, (components, json) => {
329
+ const changes = []
330
+ if (components[to] !== undefined) fail(`${COMPONENT_META_FILE} already has an entry for ${to}`, { code: 'name-taken', name: to })
331
+ if (components[name] !== undefined) {
332
+ components[to] = components[name]
333
+ delete components[name]
334
+ changes.push({ key: name, from: name, to })
335
+ }
336
+ for (const [other, value] of Object.entries(components)) {
337
+ if (isObject(value) && value.replacement === name) {
338
+ components[other] = { ...value, replacement: to }
339
+ changes.push({ key: other, from: `replacement ${name}`, to: `replacement ${to}` })
340
+ }
341
+ }
342
+ const move = plan.moves[0]
343
+ if (move && Array.isArray(json.layers?.base) && json.layers.base.includes(move.from)) {
344
+ json.layers = { ...json.layers, base: json.layers.base.map((entry) => (entry === move.from ? move.to : entry)) }
345
+ changes.push({ key: 'layers', from: move.from, to: move.to })
346
+ }
347
+ return changes
348
+ })
349
+
350
+ collectLeftovers(ctx, plan, definition, skip)
351
+ plan.verify = { name: to }
352
+ plan.summary = `Renamed ${name} to ${to}${plan.moves.length ? ` (${plan.moves[0].from} → ${plan.moves[0].to})` : ''}`
353
+ }
354
+
355
+ /** Specifier a file can import `into` with: one some file already uses, else a relative path. */
356
+ function specifierFor(ctx, abs, into, styleOf) {
357
+ const { index } = ctx
358
+ for (const [other, info] of index.infos) {
359
+ for (const binding of info.imports.values()) {
360
+ if (binding.imported === '*' || REWRITABLE_SPECIFIER.test(binding.source ?? '')) continue
361
+ if (index.sameDefinition(index.resolveLocal(other, binding.local), into)) return binding.source
362
+ }
363
+ }
364
+ let rel = toPosix(relative(dirname(abs), into.abs))
365
+ if (!rel.startsWith('.')) rel = `./${rel}`
366
+ const ext = extname(rel)
367
+ if (styleOf === 'js') return `${rel.slice(0, -ext.length)}.js`
368
+ if (styleOf === 'ext') return rel
369
+ const stripped = rel.slice(0, -ext.length)
370
+ return stripped.endsWith('/index') ? stripped.slice(0, -'/index'.length) || '.' : stripped
371
+ }
372
+
373
+ /** Edits that drop one import specifier (or the whole declaration when it is the only one). */
374
+ function removeImportSpecifier(entry, statement, spec) {
375
+ const content = entry.content
376
+ const specs = statement.specifiers ?? []
377
+ if (specs.length === 1) return { whole: true }
378
+ if (spec.type === 'ImportDefaultSpecifier') {
379
+ // `import A, { B }` → `import { B }`: the comma and the space after it go too.
380
+ let end = content.indexOf(',', spec.end) + 1
381
+ while (content[end] === ' ') end += 1
382
+ entry.edits.push({ start: spec.start, end, text: '', kind: 'import', from: content.slice(spec.start, end) })
383
+ return { whole: false }
384
+ }
385
+ const named = specs.filter((item) => item.type === 'ImportSpecifier')
386
+ const position = named.indexOf(spec)
387
+ if (named.length === 1) {
388
+ // `import A, { B } from` → `import A from`
389
+ const close = content.indexOf('}', spec.end)
390
+ const start = specs.find((item) => item.type === 'ImportDefaultSpecifier')?.end ?? spec.start
391
+ entry.edits.push({ start, end: close + 1, text: '', kind: 'import', from: content.slice(start, close + 1) })
392
+ return { whole: false }
393
+ }
394
+ const [start, end] = position < named.length - 1 ? [spec.start, named[position + 1].start] : [named[position - 1].end, spec.end]
395
+ entry.edits.push({ start, end, text: '', kind: 'import', from: content.slice(start, end) })
396
+ return { whole: false }
397
+ }
398
+
399
+ /**
400
+ * Merge / replace: move every use of `from` (outside its own file and its own component
401
+ * page) to `into`. Imports of `from` become imports of `into`; tags and references follow.
402
+ */
403
+ function planReplace(ctx, plan) {
404
+ const { index, usage } = ctx
405
+ const from = plan.from
406
+ const into = plan.into
407
+ const sameFrom = (target) => index.sameDefinition(target, from)
408
+ const sameInto = (target) => index.sameDefinition(target, into)
409
+ const intoExport = into.exportName
410
+ const ownPage = (info, ref) => info.design && usage.componentPageOwner(ref.topName) === from.name
411
+
412
+ for (const [abs, info] of index.infos) {
413
+ if (abs === from.abs) {
414
+ for (const ref of info.refs) {
415
+ if (ref.name !== from.local || ref.top === from.statementIndex || ref.kind === 'export' || ref.kind === 'export-default') continue
416
+ if (!info.statementNames[ref.top] || !sameFrom(index.resolveRef(abs, ref))) continue
417
+ plan.fileOf(abs).leftovers.push({ offset: ref.start, reason: 'declaring-file', text: from.name })
418
+ }
419
+ continue
420
+ }
421
+ const bindings = [...info.imports.values()].filter(
422
+ (binding) => binding.imported !== '*' && sameFrom(index.resolveLocal(abs, binding.local)),
423
+ )
424
+ const namespaces = [...info.imports.values()].filter((binding) => binding.imported === '*')
425
+ if (!bindings.length && !namespaces.length) continue
426
+
427
+ // The local name `into` has (or gets) in this file.
428
+ let intoLocal = null
429
+ for (const binding of info.imports.values()) {
430
+ if (binding.imported !== '*' && sameInto(index.resolveLocal(abs, binding.local))) intoLocal = binding.local
431
+ }
432
+ if (!intoLocal && abs === into.abs && into.local) intoLocal = into.local
433
+ let entry = null
434
+ const fileEntry = () => (entry ??= plan.fileOf(abs))
435
+ let importAdded = Boolean(intoLocal)
436
+
437
+ for (const binding of bindings) {
438
+ const refs = info.refs.filter((ref) => ref.name === binding.local && sameFrom(index.resolveRef(abs, ref)))
439
+ if (refs.some((ref) => ref.kind === 'export' || ref.kind === 'export-default')) {
440
+ // A barrel re-exporting it: the deprecated component stays exported.
441
+ continue
442
+ }
443
+ const uses = refs.filter((ref) => !ownPage(info, ref))
444
+ if (!uses.length) continue
445
+ const keepImport = uses.length !== refs.length
446
+ if (!intoLocal) {
447
+ if (taken(info, into.name)) {
448
+ for (const ref of uses) fileEntry().leftovers.push({ offset: ref.start, reason: 'name-conflict', text: `${into.name} is already a name in this file` })
449
+ continue
450
+ }
451
+ intoLocal = into.name
452
+ }
453
+ const sourceQuote = info.content[binding.statement.source.start]
454
+ const style = /\.[cm]?jsx?$/.test(binding.source) ? 'js' : /\.[cm]?tsx?$/.test(binding.source) ? 'ext' : 'none'
455
+ const target = index.targetOf(abs, binding.source)
456
+ const sameModule = intoExport !== 'default' && target && sameInto(index.resolveExport(target, intoExport))
457
+ const spec = sameModule ? binding.source : specifierFor(ctx, abs, into, style)
458
+ const clause = intoExport === 'default' ? intoLocal : intoLocal === intoExport ? `{ ${intoLocal} }` : `{ ${intoExport} as ${intoLocal} }`
459
+ const semi = info.content[binding.statement.end - 1] === ';' ? ';' : ''
460
+ const typePrefix = binding.statement.importKind === 'type' ? 'type ' : ''
461
+ const statementText = `import ${typePrefix}${clause} from ${sourceQuote}${spec}${sourceQuote}${semi}`
462
+ if (!keepImport) {
463
+ const removal = removeImportSpecifier(fileEntry(), binding.statement, binding.spec)
464
+ if (removal.whole) {
465
+ const text = importAdded ? '' : statementText
466
+ let end = binding.statement.end
467
+ if (!text && info.content[end] === '\n') end += 1
468
+ fileEntry().edits.push({ start: binding.statement.start, end, text, kind: 'import', from: info.content.slice(binding.statement.start, binding.statement.end) })
469
+ importAdded = true
470
+ }
471
+ }
472
+ if (!importAdded) {
473
+ const imports = info.body.filter((statement) => statement.type === 'ImportDeclaration')
474
+ const anchor = imports[imports.length - 1]
475
+ fileEntry().edits.push(
476
+ anchor
477
+ ? { start: anchor.end, end: anchor.end, text: `\n${statementText}`, kind: 'import', from: '' }
478
+ : { start: 0, end: 0, text: `${statementText}\n`, kind: 'import', from: '' },
479
+ )
480
+ importAdded = true
481
+ }
482
+ for (const ref of uses) {
483
+ if (ref.kind === 'shorthand') {
484
+ fileEntry().edits.push({ start: ref.start, end: ref.end, text: `${ref.name}: ${intoLocal}`, kind: 'ref', from: ref.name, ref: true })
485
+ } else {
486
+ const edit = renameAt(fileEntry(), ref.start, ref.name, intoLocal, ref.kind === 'jsx-close' ? 'jsx' : ref.kind)
487
+ if (edit) edit.ref = true
488
+ }
489
+ }
490
+ }
491
+ for (const binding of namespaces) {
492
+ const target = index.targetOf(abs, binding.source)
493
+ if (!target) continue
494
+ for (const ref of info.refs) {
495
+ if (ref.name !== binding.local || !ref.member || !sameFrom(index.resolveExport(target, ref.member.name))) continue
496
+ if (ownPage(info, ref)) continue
497
+ if (intoExport !== 'default' && sameInto(index.resolveExport(target, intoExport)) && !ref.member.computed) {
498
+ renameAt(fileEntry(), ref.member.start, ref.member.name, intoExport, 'member')
499
+ } else {
500
+ fileEntry().leftovers.push({ offset: ref.start, reason: 'namespace-member', text: `${ref.name}.${ref.member.name}` })
501
+ }
502
+ }
503
+ }
504
+ }
505
+ collectLeftovers(ctx, plan, from, new Set())
506
+ // Uses inside its own page and the design/components.ts key stay: the page still shows it.
507
+ for (const entry of plan.files.values()) {
508
+ entry.leftovers = entry.leftovers.filter((left) => {
509
+ if (left.reason !== 'string' && left.reason !== 'object-key') return true
510
+ return !entry.info.design
511
+ })
512
+ }
513
+ plan.verify = null
514
+ plan.notes.push(`Props are not compared: check that ${into.name} accepts the props passed at the rewritten places`)
515
+ plan.summary =
516
+ plan.op === 'merge'
517
+ ? `Merged ${from.name} into ${into.name}`
518
+ : `Replaced ${from.name} with ${into.name}`
519
+ }
520
+
521
+ /** A draft of design/components.json; `mutate(components, json)` returns the changes it made. */
522
+ function metaDraft(root, mutate) {
523
+ const abs = componentMetaPath(root)
524
+ const before = readOrNull(abs)
525
+ let json = {}
526
+ if (before !== null) {
527
+ try {
528
+ json = JSON.parse(before)
529
+ } catch {
530
+ fail(`failed to parse ${COMPONENT_META_FILE}`, { code: 'meta-invalid' })
531
+ }
532
+ }
533
+ if (!isObject(json)) json = {}
534
+ const components = isObject(json.components) ? { ...json.components } : {}
535
+ const changes = mutate(components, json)
536
+ if (!changes.length) return null
537
+ const sorted = Object.fromEntries(Object.entries(components).sort(([a], [b]) => a.localeCompare(b)))
538
+ const after = `${JSON.stringify({ ...json, components: sorted }, null, 2)}\n`
539
+ const lineOf = (key) => {
540
+ const at = (before ?? '').indexOf(`"${key}"`)
541
+ return at < 0 ? 1 : (before ?? '').slice(0, at).split('\n').length
542
+ }
543
+ return {
544
+ abs,
545
+ file: COMPONENT_META_FILE,
546
+ before,
547
+ after,
548
+ changes: changes.map((change) => ({ file: COMPONENT_META_FILE, line: lineOf(change.key), column: 1, from: change.from, to: change.to, kind: 'meta' })),
549
+ }
550
+ }
551
+
552
+ /** Deprecation written with a merge / replace: `$deprecated` + replacement. */
553
+ function deprecateDraft(root, name, into, reason, op) {
554
+ return metaDraft(root, (components) => {
555
+ const current = isObject(components[name]) ? components[name] : {}
556
+ const text = op === 'merge' ? (reason ? `Merged into ${into}: ${reason}` : `Merged into ${into}`) : reason || `Use ${into}`
557
+ components[name] = { ...current, $deprecated: text, replacement: into, deprecatedAt: new Date().toISOString() }
558
+ return [{ key: name, from: current.$deprecated ? `deprecated (${current.replacement ?? 'no replacement'})` : 'active', to: `deprecated → ${into}` }]
559
+ })
560
+ }
561
+
562
+ /** Turn a plan into per-file results: edits applied, outside-root files and unparseable results demoted. */
563
+ function finishPlan(ctx, plan) {
564
+ // The same write scope as token operations (shared/writeScope.mjs).
565
+ const isInside = (abs) => ctx.scope.isWritable(abs)
566
+ const declarationOutside = plan.op === 'rename' && !isInside(plan.from.abs)
567
+ if (declarationOutside) {
568
+ plan.notes.unshift(
569
+ `${plan.from.name} is declared outside the project root (${plan.fileOf(plan.from.abs).file}); the tool only writes inside the root and the configured writableDirs, so nothing was changed and every place is left for the agent`,
570
+ )
571
+ plan.moves = []
572
+ plan.meta = null
573
+ }
574
+ const results = []
575
+ for (const entry of plan.files.values()) {
576
+ const location = (offset) => entry.info.locationAt(offset)
577
+ const leftovers = entry.leftovers.map((left) => ({ file: entry.file, ...location(left.offset), reason: left.reason, ...(left.text ? { text: left.text } : {}) }))
578
+ let edits = entry.edits
579
+ const demote = (reason) => {
580
+ for (const edit of edits) leftovers.push({ file: entry.file, ...location(edit.start), reason, text: `${edit.from} → ${edit.text}`.slice(0, 120) })
581
+ edits = []
582
+ }
583
+ if (declarationOutside) demote('declaration-outside-project-root')
584
+ else if (edits.length && !isInside(entry.abs)) demote('outside-project-root')
585
+ let after = entry.content
586
+ if (edits.length) {
587
+ try {
588
+ after = applyEdits(entry.content, edits)
589
+ } catch {
590
+ demote('overlapping-edits')
591
+ after = entry.content
592
+ }
593
+ }
594
+ if (edits.length) {
595
+ // The result must parse, and renamed references must still resolve to the binding
596
+ // (a nested variable with the new name would capture them).
597
+ const check = analyzeSource(entry.file, after, { parseCache: new Map() })
598
+ const parsesWorse = check.errors.length > entry.info.errors.length
599
+ const expectedRefs = edits.filter((edit) => edit.ref).length
600
+ const verifyName = plan.op === 'rename' ? plan.to : null
601
+ const captured =
602
+ verifyName && expectedRefs && check.refs.filter((ref) => ref.name === verifyName).length < expectedRefs
603
+ if (parsesWorse || captured) {
604
+ demote(parsesWorse ? 'would-not-parse' : 'name-captured')
605
+ after = entry.content
606
+ }
607
+ }
608
+ const changes = edits.map((edit) => ({ file: entry.file, ...location(edit.start), from: edit.from, to: edit.text, kind: edit.kind }))
609
+ results.push({ abs: entry.abs, file: entry.file, before: entry.content, after, edits, changes, leftovers })
610
+ }
611
+ if (plan.meta && declarationOutside) plan.meta = null
612
+ return results
613
+ }
614
+
615
+ const sortPlaces = (a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column
616
+ const placeOf = (entry) => ({
617
+ file: entry.file,
618
+ line: entry.line,
619
+ column: entry.column,
620
+ ...(entry.from !== undefined ? { from: entry.from, to: entry.to } : {}),
621
+ ...(entry.reason ? { reason: entry.reason } : {}),
622
+ ...(entry.text ? { text: entry.text } : {}),
623
+ })
624
+
625
+ function buildReport(plan, results, { dryRun, design }) {
626
+ const metaChanges = plan.meta?.changes ?? []
627
+ const changes = [...results.flatMap((result) => result.changes), ...metaChanges].map(placeOf).sort(sortPlaces)
628
+ const leftovers = results.flatMap((result) => result.leftovers).map(placeOf).sort(sortPlaces)
629
+ const byFile = new Map()
630
+ for (const change of changes) {
631
+ const entry = byFile.get(change.file) ?? { file: change.file, changed: 0, left: 0 }
632
+ entry.changed += 1
633
+ byFile.set(change.file, entry)
634
+ }
635
+ for (const left of leftovers) {
636
+ const entry = byFile.get(left.file) ?? { file: left.file, changed: 0, left: 0 }
637
+ entry.left += 1
638
+ byFile.set(left.file, entry)
639
+ }
640
+ const files = [...byFile.values()].sort((a, b) => b.changed - a.changed || b.left - a.left || a.file.localeCompare(b.file))
641
+ return {
642
+ op: plan.op,
643
+ dryRun,
644
+ component: plan.from.name,
645
+ to: plan.op === 'rename' ? plan.to : plan.into.name,
646
+ ...(design ? { design } : {}),
647
+ summary: plan.summary,
648
+ counts: { changed: changes.length, leftovers: leftovers.length, files: files.filter((entry) => entry.changed).length },
649
+ files,
650
+ moves: plan.moves.map(({ from, to }) => ({ from, to })),
651
+ changes,
652
+ leftovers,
653
+ ...(plan.notes.length ? { notes: plan.notes } : {}),
654
+ }
655
+ }
656
+
657
+ /** The write scope token operations use too, with the project's `writableDirs`. */
658
+ function projectScope(root) {
659
+ let writableDirs = []
660
+ try {
661
+ writableDirs = loadTokenConfig(root).writableDirs
662
+ } catch {
663
+ // no valid token config: the root only
664
+ }
665
+ return writeScope(root, { writableDirs })
666
+ }
667
+
668
+ async function planOp(root, { op, name, to, reason }) {
669
+ if (!COMPONENT_OPS.includes(op)) fail(`unknown component operation: ${op} (expected ${COMPONENT_OPS.join(', ')})`, { code: 'invalid-args' })
670
+ const usage = await buildUsageIndex({ root })
671
+ const ctx = { root, usage, index: usage.componentIndex, scope: projectScope(root) }
672
+ const from = usage.componentDefinition(name)
673
+ if (!from) fail(`unknown component: ${name}`, { code: 'unknown-component', name })
674
+ const target = String(to ?? '').trim()
675
+ if (op === 'rename') {
676
+ if (!COMPONENT_NAME.test(target)) fail('rename needs a PascalCase name', { code: 'invalid-name', name: target })
677
+ if (target === name) fail('the new name is the current name', { code: 'same-name' })
678
+ if (usage.componentDefinition(target)) fail(`${target} already exists`, { code: 'name-taken', name: target })
679
+ const plan = createPlan(ctx, { op, from, to: target })
680
+ planRename(ctx, plan)
681
+ return { ctx, plan }
682
+ }
683
+ const into = usage.componentDefinition(target)
684
+ if (!into) fail(`unknown component: ${target}`, { code: 'unknown-component', name: target })
685
+ if (ctx.index.sameDefinition(into, from)) fail('a component cannot replace itself', { code: 'same-name' })
686
+ const plan = createPlan(ctx, { op, from, into })
687
+ planReplace(ctx, plan)
688
+ plan.meta = deprecateDraft(root, name, into.name, String(reason ?? '').trim(), op)
689
+ return { ctx, plan }
690
+ }
691
+
692
+ // ---------------------------------------------------------------------------------------
693
+ // Writing (all or nothing) and the ledger
694
+
695
+ /**
696
+ * Apply writes `{ file, toFile, fromAbs, toAbs, before, after }` in order. `before: null`
697
+ * creates the file, `after: null` deletes it, `toAbs !== fromAbs` moves it. Every file is
698
+ * checked against `before` right before it is written; any failure undoes what was done.
699
+ */
700
+ function applyWrites(writes) {
701
+ const done = []
702
+ try {
703
+ for (const write of writes) {
704
+ const current = readOrNull(write.fromAbs)
705
+ const unchanged = write.before === null ? current === null : current !== null && sha256(current) === sha256(write.before)
706
+ if (!unchanged) throw new StaleFileError(write.file)
707
+ if (write.toAbs !== write.fromAbs && existsSync(write.toAbs)) throw new StaleFileError(write.toFile)
708
+ if (write.after === null) {
709
+ rmSync(write.fromAbs)
710
+ done.push(write)
711
+ continue
712
+ }
713
+ mkdirSync(dirname(write.toAbs), { recursive: true })
714
+ writeFileAtomic(write.toAbs, write.after)
715
+ done.push(write)
716
+ if (write.toAbs !== write.fromAbs) rmSync(write.fromAbs)
717
+ }
718
+ } catch (error) {
719
+ const conflicts = undoWrites(done)
720
+ if (conflicts.length) error.restoreConflicts = conflicts
721
+ throw error
722
+ }
723
+ return done
724
+ }
725
+
726
+ function undoWrites(done) {
727
+ const conflicts = []
728
+ for (const write of [...done].reverse()) {
729
+ try {
730
+ if (write.after !== null) {
731
+ const current = readOrNull(write.toAbs)
732
+ if (current === null || sha256(current) !== sha256(write.after)) {
733
+ conflicts.push({ file: write.toFile, reason: 'changed by someone else; not restored' })
734
+ continue
735
+ }
736
+ }
737
+ if (write.before === null) {
738
+ rmSync(write.toAbs, { force: true })
739
+ } else {
740
+ writeFileAtomic(write.fromAbs, write.before)
741
+ if (write.toAbs !== write.fromAbs) rmSync(write.toAbs, { force: true })
742
+ }
743
+ } catch (error) {
744
+ conflicts.push({ file: write.file, reason: `could not restore: ${error instanceof Error ? error.message : error}` })
745
+ }
746
+ }
747
+ done.length = 0
748
+ return conflicts
749
+ }
750
+
751
+ function writesOf(plan, results) {
752
+ const moves = new Map(plan.moves.map((move) => [move.fromAbs, move]))
753
+ const writes = []
754
+ for (const result of results) {
755
+ const move = moves.get(result.abs)
756
+ if (result.after === result.before && !move) continue
757
+ writes.push({
758
+ file: result.file,
759
+ toFile: move ? move.to : result.file,
760
+ fromAbs: result.abs,
761
+ toAbs: move ? move.toAbs : result.abs,
762
+ before: result.before,
763
+ after: result.after,
764
+ undo: undoForChanges(result.before, result.after, result.edits),
765
+ })
766
+ }
767
+ for (const move of plan.moves) {
768
+ if (results.some((result) => result.abs === move.fromAbs)) continue
769
+ const content = readFileSync(move.fromAbs, 'utf8')
770
+ writes.push({ file: move.from, toFile: move.to, fromAbs: move.fromAbs, toAbs: move.toAbs, before: content, after: content, undo: [] })
771
+ }
772
+ if (plan.meta) {
773
+ writes.push({
774
+ file: plan.meta.file,
775
+ toFile: plan.meta.file,
776
+ fromAbs: plan.meta.abs,
777
+ toAbs: plan.meta.abs,
778
+ before: plan.meta.before,
779
+ after: plan.meta.after,
780
+ undo: plan.meta.before === null ? [] : undoEdits(plan.meta.before, plan.meta.after),
781
+ })
782
+ }
783
+ return writes
784
+ }
785
+
786
+ async function rebuildTokens(root) {
787
+ let config
788
+ try {
789
+ config = loadTokenConfig(root)
790
+ } catch {
791
+ return null
792
+ }
793
+ if (!existsSync(resolve(root, config.manifestOut))) return null
794
+ try {
795
+ const result = await runTokenPipeline({ root })
796
+ return { counts: result.counts, warnings: result.warnings }
797
+ } catch (error) {
798
+ // A component operation changes no token: validation problems are the project's, reported.
799
+ if (!error?.validationErrors) throw error
800
+ return { counts: error.counts, warnings: [...(error.warnings ?? []), ...error.validationErrors] }
801
+ }
802
+ }
803
+
804
+ function listDesignIds(root) {
805
+ const base = join(root, 'design')
806
+ if (!existsSync(base)) return []
807
+ let entries
808
+ try {
809
+ entries = readdirSync(base, { withFileTypes: true })
810
+ } catch {
811
+ return []
812
+ }
813
+ return entries
814
+ .filter((entry) => entry.isDirectory() && SAFE_DESIGN_ID.test(entry.name))
815
+ .filter((entry) => existsSync(join(base, entry.name, 'design.tsx')) || existsSync(join(base, entry.name, 'review.json')))
816
+ .map((entry) => entry.name)
817
+ .sort()
818
+ }
819
+
820
+ function assertLedgerWritable(root, design) {
821
+ const file = reviewFilePath(root, design)
822
+ let parsed
823
+ try {
824
+ parsed = readReviewFile(file)
825
+ } catch (error) {
826
+ fail(`cannot record the batch: ${error instanceof Error ? error.message : error}; nothing was changed`, { code: 'ledger' })
827
+ }
828
+ if (parsed && (parsed.version !== 1 || !Array.isArray(parsed.items))) {
829
+ fail(`cannot record the batch: invalid review ledger shape in ${toPosix(relative(root, file))}; nothing was changed`, { code: 'ledger' })
830
+ }
831
+ }
832
+
833
+ function recordBatch(root, design, plan, report, written, item) {
834
+ const now = new Date().toISOString()
835
+ const batchId = `components-${plan.op}-${now.replace(/[-:.TZ]/g, '').slice(0, 14)}-${randomUUID().slice(0, 6)}`
836
+ const itemId = `component-op-${batchId}`
837
+ const changed = report.counts.changed
838
+ const left = report.counts.leftovers
839
+ const note = String(item?.reason ?? '').trim()
840
+ const record = {
841
+ id: itemId,
842
+ design,
843
+ kind: 'component',
844
+ scope: 'component',
845
+ ...(item?.page ? { page: item.page } : {}),
846
+ target: { type: 'component', component: plan.from.name },
847
+ componentAction: item?.componentAction ?? plan.op,
848
+ ...(item?.componentMode ? { componentMode: item.componentMode } : {}),
849
+ from: plan.from.name,
850
+ to: report.to,
851
+ source: plan.moves[0]?.to ?? plan.fileOf(plan.from.abs).file,
852
+ body: `${plan.summary}. Tool changed ${changed} place(s) in ${report.counts.files} file(s), left ${left} for agent.${note ? ` Reason: ${note}` : ''}`,
853
+ componentOp: {
854
+ op: plan.op,
855
+ batchId,
856
+ by: 'tool',
857
+ changed,
858
+ left,
859
+ summary: plan.summary,
860
+ files: report.files,
861
+ moves: report.moves,
862
+ changes: report.changes.slice(0, MAX_ITEM_CHANGES),
863
+ ...(report.changes.length > MAX_ITEM_CHANGES ? { changesTruncated: report.changes.length } : {}),
864
+ leftovers: report.leftovers,
865
+ ...(report.notes ? { notes: report.notes } : {}),
866
+ },
867
+ status: left ? 'open' : 'resolved',
868
+ author: 'human',
869
+ createdAt: now,
870
+ updatedAt: now,
871
+ ...(left ? {} : { resolvedAt: now }),
872
+ }
873
+ const batch = {
874
+ id: batchId,
875
+ design,
876
+ createdAt: now,
877
+ itemIds: [itemId],
878
+ kind: 'component-op',
879
+ op: plan.op,
880
+ summary: plan.summary,
881
+ revert: {
882
+ files: written.map((write) => ({
883
+ file: write.toFile,
884
+ ...(write.toFile !== write.file ? { from: write.file } : {}),
885
+ ...(write.before === null ? { created: true } : {}),
886
+ beforeHash: write.before === null ? null : sha256(write.before),
887
+ afterHash: sha256(write.after),
888
+ undo: write.undo,
889
+ })),
890
+ moves: report.moves,
891
+ },
892
+ }
893
+ const { file } = mutateReview(
894
+ root,
895
+ design,
896
+ (review) => ({ ...review, items: [...review.items, record], batches: [...review.batches, batch] }),
897
+ { create: true },
898
+ )
899
+ return { batchId, itemId, status: record.status, item: record, reviewPath: file }
900
+ }
901
+
902
+ /**
903
+ * Plan and (unless `dryRun`) execute one component operation:
904
+ * rename { name, to }
905
+ * merge { name, to: <into> } also marks `name` deprecated (replacement: into)
906
+ * replace { name, to: <replacement>, reason } the deprecation with replace-all
907
+ * `design` picks the ledger; `item` adds fields to the recorded review item
908
+ * ({ componentAction, componentMode, page, reason }).
909
+ */
910
+ export async function runComponentOp({ root = process.cwd(), op, name, to, design, reason, dryRun = false, item, hooks } = {}) {
911
+ if (dryRun) {
912
+ const { ctx, plan } = await planOp(root, { op, name, to, reason })
913
+ return buildReport(plan, finishPlan(ctx, plan), { dryRun: true, design })
914
+ }
915
+ if (!design || !SAFE_DESIGN_ID.test(String(design))) fail('pass a design id to record the operation', { code: 'invalid-args' })
916
+ return locked(root, async () => {
917
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) {
918
+ const { ctx, plan } = await planOp(root, { op, name, to, reason })
919
+ const results = finishPlan(ctx, plan)
920
+ const report = buildReport(plan, results, { dryRun: false, design })
921
+ assertLedgerWritable(root, design)
922
+ hooks?.afterPlan?.()
923
+ const writes = writesOf(plan, results)
924
+ let written = []
925
+ let recorded
926
+ try {
927
+ written = applyWrites(writes)
928
+ await rebuildTokens(root)
929
+ hooks?.beforeRecord?.()
930
+ recorded = recordBatch(root, design, plan, report, written, { ...item, reason })
931
+ } catch (error) {
932
+ if (error instanceof StaleFileError && !error.restoreConflicts) {
933
+ // Someone saved a file between planning and writing; everything was undone. Re-plan.
934
+ await rebuildTokens(root).catch(() => {})
935
+ continue
936
+ }
937
+ const conflicts = [...(error.restoreConflicts ?? []), ...undoWrites(written)]
938
+ await rebuildTokens(root).catch(() => {})
939
+ fail(`${op} failed and was rolled back: ${error instanceof Error ? error.message : error}`, {
940
+ code: 'rolled-back',
941
+ ...(conflicts.length ? { notRestored: conflicts } : {}),
942
+ })
943
+ }
944
+ return { ...report, batchId: recorded.batchId, itemId: recorded.itemId, status: recorded.status, item: recorded.item, reviewPath: recorded.reviewPath }
945
+ }
946
+ fail('files kept changing while the operation ran; nothing was changed; retry', { code: 'stale' })
947
+ })
948
+ }
949
+
950
+ // ---------------------------------------------------------------------------------------
951
+ // Revert
952
+
953
+ /**
954
+ * A batch path as an absolute path in the write scope (shared/writeScope.mjs: inside the root
955
+ * or a `writableDirs` entry, never through a symlink), or a reason. review.json is editable
956
+ * by hand, so revert data is never trusted. The file may be missing (a rename's old name,
957
+ * moved back to; a deleted file is reported as a conflict by the caller).
958
+ */
959
+ function revertPath(scope, file) {
960
+ if (typeof file !== 'string' || !file || file.includes('\0')) return { reason: 'invalid path' }
961
+ const posix = file.replaceAll('\\', '/')
962
+ if (isAbsolute(file) || posix.startsWith('/') || /^[a-zA-Z]:/.test(posix)) return { reason: 'path outside the project' }
963
+ return scope.check(posix, { missing: true })
964
+ }
965
+
966
+ /** Undo a component batch: restore every file, move renamed files back, archive the item. */
967
+ export function revertComponentBatch({ root = process.cwd(), batch: batchId, design, force = false, dryRun = false } = {}) {
968
+ return locked(root, async () => {
969
+ const id = String(batchId ?? '').trim()
970
+ if (!id) fail('<batch> is required', { code: 'invalid-args' })
971
+ const designs = design ? [String(design)] : listDesignIds(root)
972
+ let found = null
973
+ for (const candidate of designs) {
974
+ if (!SAFE_DESIGN_ID.test(candidate)) fail(`invalid design id: ${candidate}`, { code: 'invalid-args' })
975
+ const review = readReviewFile(reviewFilePath(root, candidate))
976
+ const batch = review?.batches?.find((entry) => entry.id === id)
977
+ if (batch) {
978
+ found = { design: candidate, batch }
979
+ break
980
+ }
981
+ }
982
+ if (!found) fail(`batch not found: ${id}`, { code: 'not-found' })
983
+ const { batch } = found
984
+ if (batch.kind !== 'component-op' || !Array.isArray(batch.revert?.files)) fail(`${id} is not a component batch`, { code: 'invalid-args' })
985
+ if (batch.revertedAt) fail(`${id} was already reverted at ${batch.revertedAt}`, { code: 'reverted' })
986
+ const scope = projectScope(root)
987
+
988
+ const files = batch.revert.files.map((entry) => {
989
+ const target = revertPath(scope, entry?.file)
990
+ const origin = entry?.from ? revertPath(scope, entry.from) : target
991
+ if (!target.abs || !origin.abs) return { file: String(entry?.file), ok: false, unsafe: true, reason: target.reason ?? origin.reason }
992
+ const current = readOrNull(target.abs)
993
+ if (current === null) return { file: entry.file, ok: false, reason: 'file is missing' }
994
+ if (sha256(current) !== entry.afterHash) return { file: entry.file, ok: false, reason: 'changed since the batch' }
995
+ if (entry.from && existsSync(origin.abs)) return { file: entry.file, ok: false, reason: `${entry.from} exists again` }
996
+ let before = null
997
+ if (!entry.created) {
998
+ try {
999
+ before = applyEdits(current, Array.isArray(entry.undo) ? entry.undo : [])
1000
+ } catch {
1001
+ return { file: entry.file, ok: false, reason: 'undo does not apply' }
1002
+ }
1003
+ if (sha256(before) !== entry.beforeHash) return { file: entry.file, ok: false, reason: 'undo does not reproduce the original' }
1004
+ }
1005
+ return {
1006
+ ok: true,
1007
+ file: entry.file,
1008
+ write: { file: entry.file, toFile: entry.from ?? entry.file, fromAbs: target.abs, toAbs: origin.abs, before: current, after: before },
1009
+ }
1010
+ })
1011
+ const unsafe = files.filter((entry) => entry.unsafe)
1012
+ if (unsafe.length) fail(`refusing to revert ${id}: ${unsafe.map((entry) => `${entry.file} (${entry.reason})`).join(', ')}`, { code: 'unsafe' })
1013
+ const conflicts = files.filter((entry) => !entry.ok).map((entry) => ({ file: entry.file, reason: entry.reason }))
1014
+ const report = {
1015
+ op: 'revert',
1016
+ dryRun,
1017
+ design: found.design,
1018
+ batch: id,
1019
+ summary: batch.summary,
1020
+ files: files.filter((entry) => entry.ok).map((entry) => entry.file),
1021
+ moves: (batch.revert.moves ?? []).map((move) => ({ from: move.to, to: move.from })),
1022
+ conflicts,
1023
+ }
1024
+ if (conflicts.length && !force) {
1025
+ const message = `cannot revert ${id}: ${conflicts.map((entry) => `${entry.file} (${entry.reason})`).join(', ')}. Re-run with --force to revert only the unchanged files.`
1026
+ if (dryRun) return { ...report, refused: message }
1027
+ fail(message, { code: 'conflict', ...report })
1028
+ }
1029
+ if (dryRun) return report
1030
+ assertLedgerWritable(root, found.design)
1031
+ const now = new Date().toISOString()
1032
+ let written = []
1033
+ try {
1034
+ written = applyWrites(files.filter((entry) => entry.ok).map((entry) => entry.write))
1035
+ await rebuildTokens(root)
1036
+ const itemIds = new Set(batch.itemIds ?? [])
1037
+ mutateReview(root, found.design, (review) => {
1038
+ const current = review.batches.find((entry) => entry.id === id)
1039
+ if (!current) throw new Error(`batch ${id} disappeared from the ledger`)
1040
+ if (current.revertedAt) throw new Error(`${id} was already reverted at ${current.revertedAt}`)
1041
+ return {
1042
+ ...review,
1043
+ items: review.items.map((item) =>
1044
+ itemIds.has(item.id)
1045
+ ? {
1046
+ ...item,
1047
+ status: 'archived',
1048
+ archivedAt: now,
1049
+ updatedAt: now,
1050
+ ...(item.componentOp ? { componentOp: { ...item.componentOp, revertedAt: now } } : {}),
1051
+ }
1052
+ : item,
1053
+ ),
1054
+ batches: review.batches.map((entry) =>
1055
+ entry.id === id ? { ...entry, revertedAt: now, ...(conflicts.length ? { revertSkipped: conflicts } : {}) } : entry,
1056
+ ),
1057
+ }
1058
+ })
1059
+ } catch (error) {
1060
+ const notRestored = [...(error.restoreConflicts ?? []), ...undoWrites(written)]
1061
+ await rebuildTokens(root).catch(() => {})
1062
+ fail(`revert failed and was rolled back: ${error instanceof Error ? error.message : error}`, {
1063
+ code: 'rolled-back',
1064
+ ...(notRestored.length ? { notRestored } : {}),
1065
+ })
1066
+ }
1067
+ return { ...report, revertedAt: now }
1068
+ })
1069
+ }