@chinhae/atw-cli 0.1.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 (710) hide show
  1. package/COPYRIGHT +14 -0
  2. package/LICENSE +77 -0
  3. package/README.md +122 -0
  4. package/bin/atw.js +3 -0
  5. package/dist/cli/index.d.ts +3 -0
  6. package/dist/cli/index.d.ts.map +1 -0
  7. package/dist/cli/index.js +299 -0
  8. package/dist/cli/index.js.map +1 -0
  9. package/dist/commands/ablate.d.ts +14 -0
  10. package/dist/commands/ablate.d.ts.map +1 -0
  11. package/dist/commands/ablate.js +307 -0
  12. package/dist/commands/ablate.js.map +1 -0
  13. package/dist/commands/channel/adapters/claude.d.ts +53 -0
  14. package/dist/commands/channel/adapters/claude.d.ts.map +1 -0
  15. package/dist/commands/channel/adapters/claude.js +225 -0
  16. package/dist/commands/channel/adapters/claude.js.map +1 -0
  17. package/dist/commands/channel/adapters/codex.d.ts +93 -0
  18. package/dist/commands/channel/adapters/codex.d.ts.map +1 -0
  19. package/dist/commands/channel/adapters/codex.js +573 -0
  20. package/dist/commands/channel/adapters/codex.js.map +1 -0
  21. package/dist/commands/channel/adapters/index.d.ts +94 -0
  22. package/dist/commands/channel/adapters/index.d.ts.map +1 -0
  23. package/dist/commands/channel/adapters/index.js +116 -0
  24. package/dist/commands/channel/adapters/index.js.map +1 -0
  25. package/dist/commands/channel/adapters/types.d.ts +33 -0
  26. package/dist/commands/channel/adapters/types.d.ts.map +1 -0
  27. package/dist/commands/channel/adapters/types.js +2 -0
  28. package/dist/commands/channel/adapters/types.js.map +1 -0
  29. package/dist/commands/channel/agent-loader.d.ts +32 -0
  30. package/dist/commands/channel/agent-loader.d.ts.map +1 -0
  31. package/dist/commands/channel/agent-loader.js +158 -0
  32. package/dist/commands/channel/agent-loader.js.map +1 -0
  33. package/dist/commands/channel/context-loader.d.ts +26 -0
  34. package/dist/commands/channel/context-loader.d.ts.map +1 -0
  35. package/dist/commands/channel/context-loader.js +311 -0
  36. package/dist/commands/channel/context-loader.js.map +1 -0
  37. package/dist/commands/channel/context-trust.d.ts +31 -0
  38. package/dist/commands/channel/context-trust.d.ts.map +1 -0
  39. package/dist/commands/channel/context-trust.js +139 -0
  40. package/dist/commands/channel/context-trust.js.map +1 -0
  41. package/dist/commands/channel/context.d.ts +16 -0
  42. package/dist/commands/channel/context.d.ts.map +1 -0
  43. package/dist/commands/channel/context.js +83 -0
  44. package/dist/commands/channel/context.js.map +1 -0
  45. package/dist/commands/channel/create.d.ts +27 -0
  46. package/dist/commands/channel/create.d.ts.map +1 -0
  47. package/dist/commands/channel/create.js +39 -0
  48. package/dist/commands/channel/create.js.map +1 -0
  49. package/dist/commands/channel/dev-parse-trace.d.ts +14 -0
  50. package/dist/commands/channel/dev-parse-trace.d.ts.map +1 -0
  51. package/dist/commands/channel/dev-parse-trace.js +70 -0
  52. package/dist/commands/channel/dev-parse-trace.js.map +1 -0
  53. package/dist/commands/channel/guard.d.ts +150 -0
  54. package/dist/commands/channel/guard.d.ts.map +1 -0
  55. package/dist/commands/channel/guard.js +479 -0
  56. package/dist/commands/channel/guard.js.map +1 -0
  57. package/dist/commands/channel/index.d.ts +3 -0
  58. package/dist/commands/channel/index.d.ts.map +1 -0
  59. package/dist/commands/channel/index.js +535 -0
  60. package/dist/commands/channel/index.js.map +1 -0
  61. package/dist/commands/channel/interrupt.d.ts +10 -0
  62. package/dist/commands/channel/interrupt.d.ts.map +1 -0
  63. package/dist/commands/channel/interrupt.js +22 -0
  64. package/dist/commands/channel/interrupt.js.map +1 -0
  65. package/dist/commands/channel/kill.d.ts +7 -0
  66. package/dist/commands/channel/kill.d.ts.map +1 -0
  67. package/dist/commands/channel/kill.js +130 -0
  68. package/dist/commands/channel/kill.js.map +1 -0
  69. package/dist/commands/channel/list.d.ts +17 -0
  70. package/dist/commands/channel/list.d.ts.map +1 -0
  71. package/dist/commands/channel/list.js +233 -0
  72. package/dist/commands/channel/list.js.map +1 -0
  73. package/dist/commands/channel/messages.d.ts +15 -0
  74. package/dist/commands/channel/messages.d.ts.map +1 -0
  75. package/dist/commands/channel/messages.js +245 -0
  76. package/dist/commands/channel/messages.js.map +1 -0
  77. package/dist/commands/channel/rm.d.ts +27 -0
  78. package/dist/commands/channel/rm.d.ts.map +1 -0
  79. package/dist/commands/channel/rm.js +216 -0
  80. package/dist/commands/channel/rm.js.map +1 -0
  81. package/dist/commands/channel/run.d.ts +30 -0
  82. package/dist/commands/channel/run.d.ts.map +1 -0
  83. package/dist/commands/channel/run.js +130 -0
  84. package/dist/commands/channel/run.js.map +1 -0
  85. package/dist/commands/channel/send.d.ts +11 -0
  86. package/dist/commands/channel/send.d.ts.map +1 -0
  87. package/dist/commands/channel/send.js +24 -0
  88. package/dist/commands/channel/send.js.map +1 -0
  89. package/dist/commands/channel/spawn.d.ts +43 -0
  90. package/dist/commands/channel/spawn.d.ts.map +1 -0
  91. package/dist/commands/channel/spawn.js +247 -0
  92. package/dist/commands/channel/spawn.js.map +1 -0
  93. package/dist/commands/channel/store/events.d.ts +22 -0
  94. package/dist/commands/channel/store/events.d.ts.map +1 -0
  95. package/dist/commands/channel/store/events.js +43 -0
  96. package/dist/commands/channel/store/events.js.map +1 -0
  97. package/dist/commands/channel/store/filter.d.ts +3 -0
  98. package/dist/commands/channel/store/filter.d.ts.map +1 -0
  99. package/dist/commands/channel/store/filter.js +2 -0
  100. package/dist/commands/channel/store/filter.js.map +1 -0
  101. package/dist/commands/channel/store/lock.d.ts +23 -0
  102. package/dist/commands/channel/store/lock.d.ts.map +1 -0
  103. package/dist/commands/channel/store/lock.js +99 -0
  104. package/dist/commands/channel/store/lock.js.map +1 -0
  105. package/dist/commands/channel/store/paths.d.ts +77 -0
  106. package/dist/commands/channel/store/paths.d.ts.map +1 -0
  107. package/dist/commands/channel/store/paths.js +272 -0
  108. package/dist/commands/channel/store/paths.js.map +1 -0
  109. package/dist/commands/channel/store/schema.d.ts +27 -0
  110. package/dist/commands/channel/store/schema.d.ts.map +1 -0
  111. package/dist/commands/channel/store/schema.js +34 -0
  112. package/dist/commands/channel/store/schema.js.map +1 -0
  113. package/dist/commands/channel/store/thread-state.d.ts +5 -0
  114. package/dist/commands/channel/store/thread-state.d.ts.map +1 -0
  115. package/dist/commands/channel/store/thread-state.js +16 -0
  116. package/dist/commands/channel/store/thread-state.js.map +1 -0
  117. package/dist/commands/channel/store/watch.d.ts +19 -0
  118. package/dist/commands/channel/store/watch.d.ts.map +1 -0
  119. package/dist/commands/channel/store/watch.js +153 -0
  120. package/dist/commands/channel/store/watch.js.map +1 -0
  121. package/dist/commands/channel/supervisor/idle.d.ts +45 -0
  122. package/dist/commands/channel/supervisor/idle.d.ts.map +1 -0
  123. package/dist/commands/channel/supervisor/idle.js +70 -0
  124. package/dist/commands/channel/supervisor/idle.js.map +1 -0
  125. package/dist/commands/channel/supervisor/inbox.d.ts +30 -0
  126. package/dist/commands/channel/supervisor/inbox.d.ts.map +1 -0
  127. package/dist/commands/channel/supervisor/inbox.js +160 -0
  128. package/dist/commands/channel/supervisor/inbox.js.map +1 -0
  129. package/dist/commands/channel/supervisor/shutdown.d.ts +68 -0
  130. package/dist/commands/channel/supervisor/shutdown.d.ts.map +1 -0
  131. package/dist/commands/channel/supervisor/shutdown.js +146 -0
  132. package/dist/commands/channel/supervisor/shutdown.js.map +1 -0
  133. package/dist/commands/channel/supervisor/stdout.d.ts +71 -0
  134. package/dist/commands/channel/supervisor/stdout.d.ts.map +1 -0
  135. package/dist/commands/channel/supervisor/stdout.js +229 -0
  136. package/dist/commands/channel/supervisor/stdout.js.map +1 -0
  137. package/dist/commands/channel/supervisor/turns.d.ts +31 -0
  138. package/dist/commands/channel/supervisor/turns.d.ts.map +1 -0
  139. package/dist/commands/channel/supervisor/turns.js +45 -0
  140. package/dist/commands/channel/supervisor/turns.js.map +1 -0
  141. package/dist/commands/channel/supervisor/warning.d.ts +48 -0
  142. package/dist/commands/channel/supervisor/warning.d.ts.map +1 -0
  143. package/dist/commands/channel/supervisor/warning.js +77 -0
  144. package/dist/commands/channel/supervisor/warning.js.map +1 -0
  145. package/dist/commands/channel/supervisor.d.ts +91 -0
  146. package/dist/commands/channel/supervisor.d.ts.map +1 -0
  147. package/dist/commands/channel/supervisor.js +463 -0
  148. package/dist/commands/channel/supervisor.js.map +1 -0
  149. package/dist/commands/channel/text-body.d.ts +13 -0
  150. package/dist/commands/channel/text-body.d.ts.map +1 -0
  151. package/dist/commands/channel/text-body.js +47 -0
  152. package/dist/commands/channel/text-body.js.map +1 -0
  153. package/dist/commands/channel/threads.d.ts +39 -0
  154. package/dist/commands/channel/threads.d.ts.map +1 -0
  155. package/dist/commands/channel/threads.js +106 -0
  156. package/dist/commands/channel/threads.js.map +1 -0
  157. package/dist/commands/channel/title.d.ts +12 -0
  158. package/dist/commands/channel/title.d.ts.map +1 -0
  159. package/dist/commands/channel/title.js +24 -0
  160. package/dist/commands/channel/title.js.map +1 -0
  161. package/dist/commands/channel/wait.d.ts +17 -0
  162. package/dist/commands/channel/wait.d.ts.map +1 -0
  163. package/dist/commands/channel/wait.js +75 -0
  164. package/dist/commands/channel/wait.js.map +1 -0
  165. package/dist/commands/init.d.ts +71 -0
  166. package/dist/commands/init.d.ts.map +1 -0
  167. package/dist/commands/init.js +1612 -0
  168. package/dist/commands/init.js.map +1 -0
  169. package/dist/commands/mem.d.ts +30 -0
  170. package/dist/commands/mem.d.ts.map +1 -0
  171. package/dist/commands/mem.js +423 -0
  172. package/dist/commands/mem.js.map +1 -0
  173. package/dist/commands/uninstall.d.ts +36 -0
  174. package/dist/commands/uninstall.d.ts.map +1 -0
  175. package/dist/commands/uninstall.js +205 -0
  176. package/dist/commands/uninstall.js.map +1 -0
  177. package/dist/commands/update.d.ts +133 -0
  178. package/dist/commands/update.d.ts.map +1 -0
  179. package/dist/commands/update.js +2255 -0
  180. package/dist/commands/update.js.map +1 -0
  181. package/dist/commands/upgrade.d.ts +28 -0
  182. package/dist/commands/upgrade.d.ts.map +1 -0
  183. package/dist/commands/upgrade.js +84 -0
  184. package/dist/commands/upgrade.js.map +1 -0
  185. package/dist/commands/workflow.d.ts +35 -0
  186. package/dist/commands/workflow.d.ts.map +1 -0
  187. package/dist/commands/workflow.js +232 -0
  188. package/dist/commands/workflow.js.map +1 -0
  189. package/dist/configurators/antigravity.d.ts +7 -0
  190. package/dist/configurators/antigravity.d.ts.map +1 -0
  191. package/dist/configurators/antigravity.js +11 -0
  192. package/dist/configurators/antigravity.js.map +1 -0
  193. package/dist/configurators/claude.d.ts +23 -0
  194. package/dist/configurators/claude.d.ts.map +1 -0
  195. package/dist/configurators/claude.js +123 -0
  196. package/dist/configurators/claude.js.map +1 -0
  197. package/dist/configurators/codebuddy.d.ts +10 -0
  198. package/dist/configurators/codebuddy.d.ts.map +1 -0
  199. package/dist/configurators/codebuddy.js +24 -0
  200. package/dist/configurators/codebuddy.js.map +1 -0
  201. package/dist/configurators/codex.d.ts +57 -0
  202. package/dist/configurators/codex.d.ts.map +1 -0
  203. package/dist/configurators/codex.js +170 -0
  204. package/dist/configurators/codex.js.map +1 -0
  205. package/dist/configurators/copilot.d.ts +18 -0
  206. package/dist/configurators/copilot.d.ts.map +1 -0
  207. package/dist/configurators/copilot.js +50 -0
  208. package/dist/configurators/copilot.js.map +1 -0
  209. package/dist/configurators/cursor.d.ts +10 -0
  210. package/dist/configurators/cursor.d.ts.map +1 -0
  211. package/dist/configurators/cursor.js +23 -0
  212. package/dist/configurators/cursor.js.map +1 -0
  213. package/dist/configurators/devin.d.ts +8 -0
  214. package/dist/configurators/devin.d.ts.map +1 -0
  215. package/dist/configurators/devin.js +12 -0
  216. package/dist/configurators/devin.js.map +1 -0
  217. package/dist/configurators/droid.d.ts +10 -0
  218. package/dist/configurators/droid.d.ts.map +1 -0
  219. package/dist/configurators/droid.js +24 -0
  220. package/dist/configurators/droid.js.map +1 -0
  221. package/dist/configurators/dsh.d.ts +29 -0
  222. package/dist/configurators/dsh.d.ts.map +1 -0
  223. package/dist/configurators/dsh.js +64 -0
  224. package/dist/configurators/dsh.js.map +1 -0
  225. package/dist/configurators/gemini.d.ts +19 -0
  226. package/dist/configurators/gemini.d.ts.map +1 -0
  227. package/dist/configurators/gemini.js +40 -0
  228. package/dist/configurators/gemini.js.map +1 -0
  229. package/dist/configurators/grok.d.ts +17 -0
  230. package/dist/configurators/grok.d.ts.map +1 -0
  231. package/dist/configurators/grok.js +38 -0
  232. package/dist/configurators/grok.js.map +1 -0
  233. package/dist/configurators/index.d.ts +68 -0
  234. package/dist/configurators/index.d.ts.map +1 -0
  235. package/dist/configurators/index.js +191 -0
  236. package/dist/configurators/index.js.map +1 -0
  237. package/dist/configurators/kilo.d.ts +7 -0
  238. package/dist/configurators/kilo.d.ts.map +1 -0
  239. package/dist/configurators/kilo.js +11 -0
  240. package/dist/configurators/kilo.js.map +1 -0
  241. package/dist/configurators/kimi.d.ts +26 -0
  242. package/dist/configurators/kimi.d.ts.map +1 -0
  243. package/dist/configurators/kimi.js +74 -0
  244. package/dist/configurators/kimi.js.map +1 -0
  245. package/dist/configurators/kiro.d.ts +11 -0
  246. package/dist/configurators/kiro.d.ts.map +1 -0
  247. package/dist/configurators/kiro.js +30 -0
  248. package/dist/configurators/kiro.js.map +1 -0
  249. package/dist/configurators/omp.d.ts +6 -0
  250. package/dist/configurators/omp.d.ts.map +1 -0
  251. package/dist/configurators/omp.js +28 -0
  252. package/dist/configurators/omp.js.map +1 -0
  253. package/dist/configurators/opencode.d.ts +5 -0
  254. package/dist/configurators/opencode.d.ts.map +1 -0
  255. package/dist/configurators/opencode.js +80 -0
  256. package/dist/configurators/opencode.js.map +1 -0
  257. package/dist/configurators/pi.d.ts +5 -0
  258. package/dist/configurators/pi.d.ts.map +1 -0
  259. package/dist/configurators/pi.js +39 -0
  260. package/dist/configurators/pi.js.map +1 -0
  261. package/dist/configurators/qoder.d.ts +12 -0
  262. package/dist/configurators/qoder.d.ts.map +1 -0
  263. package/dist/configurators/qoder.js +30 -0
  264. package/dist/configurators/qoder.js.map +1 -0
  265. package/dist/configurators/reasonix.d.ts +17 -0
  266. package/dist/configurators/reasonix.d.ts.map +1 -0
  267. package/dist/configurators/reasonix.js +37 -0
  268. package/dist/configurators/reasonix.js.map +1 -0
  269. package/dist/configurators/shared.d.ts +196 -0
  270. package/dist/configurators/shared.d.ts.map +1 -0
  271. package/dist/configurators/shared.js +600 -0
  272. package/dist/configurators/shared.js.map +1 -0
  273. package/dist/configurators/snow.d.ts +25 -0
  274. package/dist/configurators/snow.d.ts.map +1 -0
  275. package/dist/configurators/snow.js +69 -0
  276. package/dist/configurators/snow.js.map +1 -0
  277. package/dist/configurators/trae.d.ts +16 -0
  278. package/dist/configurators/trae.d.ts.map +1 -0
  279. package/dist/configurators/trae.js +34 -0
  280. package/dist/configurators/trae.js.map +1 -0
  281. package/dist/configurators/workflow.d.ts +51 -0
  282. package/dist/configurators/workflow.d.ts.map +1 -0
  283. package/dist/configurators/workflow.js +210 -0
  284. package/dist/configurators/workflow.js.map +1 -0
  285. package/dist/configurators/zcode.d.ts +19 -0
  286. package/dist/configurators/zcode.d.ts.map +1 -0
  287. package/dist/configurators/zcode.js +51 -0
  288. package/dist/configurators/zcode.js.map +1 -0
  289. package/dist/constants/paths.d.ts +74 -0
  290. package/dist/constants/paths.d.ts.map +1 -0
  291. package/dist/constants/paths.js +83 -0
  292. package/dist/constants/paths.js.map +1 -0
  293. package/dist/constants/version.d.ts +9 -0
  294. package/dist/constants/version.d.ts.map +1 -0
  295. package/dist/constants/version.js +15 -0
  296. package/dist/constants/version.js.map +1 -0
  297. package/dist/index.d.ts +9 -0
  298. package/dist/index.d.ts.map +1 -0
  299. package/dist/index.js +9 -0
  300. package/dist/index.js.map +1 -0
  301. package/dist/migrations/index.d.ts +65 -0
  302. package/dist/migrations/index.d.ts.map +1 -0
  303. package/dist/migrations/index.js +202 -0
  304. package/dist/migrations/index.js.map +1 -0
  305. package/dist/templates/atw/agents/implement-agent.md +69 -0
  306. package/dist/templates/atw/agents/review.md +68 -0
  307. package/dist/templates/atw/config.yaml +158 -0
  308. package/dist/templates/atw/gitattributes.txt +9 -0
  309. package/dist/templates/atw/gitignore.txt +32 -0
  310. package/dist/templates/atw/index.d.ts +70 -0
  311. package/dist/templates/atw/index.d.ts.map +1 -0
  312. package/dist/templates/atw/index.js +137 -0
  313. package/dist/templates/atw/index.js.map +1 -0
  314. package/dist/templates/atw/scripts/__init__.py +5 -0
  315. package/dist/templates/atw/scripts/add_session.py +1545 -0
  316. package/dist/templates/atw/scripts/common/__init__.py +94 -0
  317. package/dist/templates/atw/scripts/common/active_task.py +857 -0
  318. package/dist/templates/atw/scripts/common/atw_config.py +239 -0
  319. package/dist/templates/atw/scripts/common/cli_adapter.py +949 -0
  320. package/dist/templates/atw/scripts/common/config.py +482 -0
  321. package/dist/templates/atw/scripts/common/developer.py +192 -0
  322. package/dist/templates/atw/scripts/common/git.py +203 -0
  323. package/dist/templates/atw/scripts/common/git_context.py +106 -0
  324. package/dist/templates/atw/scripts/common/io.py +160 -0
  325. package/dist/templates/atw/scripts/common/log.py +45 -0
  326. package/dist/templates/atw/scripts/common/packages_context.py +238 -0
  327. package/dist/templates/atw/scripts/common/paths.py +543 -0
  328. package/dist/templates/atw/scripts/common/safe_commit.py +322 -0
  329. package/dist/templates/atw/scripts/common/session_context.py +892 -0
  330. package/dist/templates/atw/scripts/common/task_context.py +470 -0
  331. package/dist/templates/atw/scripts/common/task_queue.py +188 -0
  332. package/dist/templates/atw/scripts/common/task_store.py +1940 -0
  333. package/dist/templates/atw/scripts/common/task_utils.py +498 -0
  334. package/dist/templates/atw/scripts/common/tasks.py +122 -0
  335. package/dist/templates/atw/scripts/common/types.py +110 -0
  336. package/dist/templates/atw/scripts/common/workflow_phase.py +242 -0
  337. package/dist/templates/atw/scripts/get_context.py +16 -0
  338. package/dist/templates/atw/scripts/get_developer.py +26 -0
  339. package/dist/templates/atw/scripts/github_sync.py +391 -0
  340. package/dist/templates/atw/scripts/hooks/linear_sync.py +243 -0
  341. package/dist/templates/atw/scripts/init_developer.py +51 -0
  342. package/dist/templates/atw/scripts/task.py +833 -0
  343. package/dist/templates/atw/scripts/tickets.py +495 -0
  344. package/dist/templates/atw/tasks/.gitkeep +0 -0
  345. package/dist/templates/atw/workflow.md +754 -0
  346. package/dist/templates/claude/agents/atw-implement-agent.md +107 -0
  347. package/dist/templates/claude/agents/atw-review.md +113 -0
  348. package/dist/templates/claude/hooks/statusline.py +332 -0
  349. package/dist/templates/claude/index.d.ts +31 -0
  350. package/dist/templates/claude/index.d.ts.map +1 -0
  351. package/dist/templates/claude/index.js +57 -0
  352. package/dist/templates/claude/index.js.map +1 -0
  353. package/dist/templates/claude/settings.json +73 -0
  354. package/dist/templates/codebuddy/agents/atw-implement-agent.md +107 -0
  355. package/dist/templates/codebuddy/agents/atw-review.md +113 -0
  356. package/dist/templates/codebuddy/index.d.ts +15 -0
  357. package/dist/templates/codebuddy/index.d.ts.map +1 -0
  358. package/dist/templates/codebuddy/index.js +15 -0
  359. package/dist/templates/codebuddy/index.js.map +1 -0
  360. package/dist/templates/codebuddy/settings.json +69 -0
  361. package/dist/templates/codex/agents/atw-implement-agent.toml +37 -0
  362. package/dist/templates/codex/agents/atw-review.toml +56 -0
  363. package/dist/templates/codex/config.toml +39 -0
  364. package/dist/templates/codex/hooks/session-start.py +514 -0
  365. package/dist/templates/codex/hooks.json +27 -0
  366. package/dist/templates/codex/index.d.ts +35 -0
  367. package/dist/templates/codex/index.d.ts.map +1 -0
  368. package/dist/templates/codex/index.js +67 -0
  369. package/dist/templates/codex/index.js.map +1 -0
  370. package/dist/templates/common/bundled-skills/atw-askme/SKILL.md +7 -0
  371. package/dist/templates/common/bundled-skills/atw-askme/agents/openai.yaml +5 -0
  372. package/dist/templates/common/bundled-skills/atw-askme-with-docs/SKILL.md +7 -0
  373. package/dist/templates/common/bundled-skills/atw-askme-with-docs/agents/openai.yaml +5 -0
  374. package/dist/templates/common/bundled-skills/atw-channel/SKILL.md +67 -0
  375. package/dist/templates/common/bundled-skills/atw-channel/references/command-reference.md +480 -0
  376. package/dist/templates/common/bundled-skills/atw-channel/references/forum.md +233 -0
  377. package/dist/templates/common/bundled-skills/atw-channel/references/progress-debugging.md +226 -0
  378. package/dist/templates/common/bundled-skills/atw-channel/references/workers.md +274 -0
  379. package/dist/templates/common/bundled-skills/atw-channel/references/workflows.md +125 -0
  380. package/dist/templates/common/bundled-skills/atw-code-review/SKILL.md +113 -0
  381. package/dist/templates/common/bundled-skills/atw-code-review/agents/openai.yaml +3 -0
  382. package/dist/templates/common/bundled-skills/atw-codebase-design/DEEPENING.md +37 -0
  383. package/dist/templates/common/bundled-skills/atw-codebase-design/DESIGN-IT-TWICE.md +44 -0
  384. package/dist/templates/common/bundled-skills/atw-codebase-design/SKILL.md +114 -0
  385. package/dist/templates/common/bundled-skills/atw-codebase-design/agents/openai.yaml +3 -0
  386. package/dist/templates/common/bundled-skills/atw-diagnosing-bugs/SKILL.md +138 -0
  387. package/dist/templates/common/bundled-skills/atw-diagnosing-bugs/agents/openai.yaml +3 -0
  388. package/dist/templates/common/bundled-skills/atw-diagnosing-bugs/scripts/hitl-loop.template.sh +44 -0
  389. package/dist/templates/common/bundled-skills/atw-domain-modeling/ADR-FORMAT.md +47 -0
  390. package/dist/templates/common/bundled-skills/atw-domain-modeling/CONTEXT-FORMAT.md +60 -0
  391. package/dist/templates/common/bundled-skills/atw-domain-modeling/SKILL.md +74 -0
  392. package/dist/templates/common/bundled-skills/atw-domain-modeling/agents/openai.yaml +3 -0
  393. package/dist/templates/common/bundled-skills/atw-handoff/SKILL.md +16 -0
  394. package/dist/templates/common/bundled-skills/atw-handoff/agents/openai.yaml +5 -0
  395. package/dist/templates/common/bundled-skills/atw-implement/SKILL.md +21 -0
  396. package/dist/templates/common/bundled-skills/atw-implement/agents/openai.yaml +5 -0
  397. package/dist/templates/common/bundled-skills/atw-improve-codebase-architecture/HTML-REPORT.md +123 -0
  398. package/dist/templates/common/bundled-skills/atw-improve-codebase-architecture/SKILL.md +71 -0
  399. package/dist/templates/common/bundled-skills/atw-improve-codebase-architecture/agents/openai.yaml +5 -0
  400. package/dist/templates/common/bundled-skills/atw-init-repo/SKILL.md +130 -0
  401. package/dist/templates/common/bundled-skills/atw-init-repo/references/domain.md +51 -0
  402. package/dist/templates/common/bundled-skills/atw-init-repo/references/issue-tracker-atw-local.md +133 -0
  403. package/dist/templates/common/bundled-skills/atw-init-repo/references/issue-tracker-atw.md +109 -0
  404. package/dist/templates/common/bundled-skills/atw-init-repo/references/issue-tracker-github.md +45 -0
  405. package/dist/templates/common/bundled-skills/atw-init-repo/references/issue-tracker-gitlab.md +46 -0
  406. package/dist/templates/common/bundled-skills/atw-init-repo/references/issue-tracker-local.md +30 -0
  407. package/dist/templates/common/bundled-skills/atw-init-repo/references/triage-labels.md +15 -0
  408. package/dist/templates/common/bundled-skills/atw-interview/SKILL.md +22 -0
  409. package/dist/templates/common/bundled-skills/atw-interview/agents/openai.yaml +3 -0
  410. package/dist/templates/common/bundled-skills/atw-map/SKILL.md +128 -0
  411. package/dist/templates/common/bundled-skills/atw-map/agents/openai.yaml +5 -0
  412. package/dist/templates/common/bundled-skills/atw-merge/SKILL.md +14 -0
  413. package/dist/templates/common/bundled-skills/atw-merge/agents/openai.yaml +3 -0
  414. package/dist/templates/common/bundled-skills/atw-meta/SKILL.md +85 -0
  415. package/dist/templates/common/bundled-skills/atw-meta/references/customize-local/add-project-local-conventions.md +83 -0
  416. package/dist/templates/common/bundled-skills/atw-meta/references/customize-local/change-agents.md +55 -0
  417. package/dist/templates/common/bundled-skills/atw-meta/references/customize-local/change-context-loading.md +80 -0
  418. package/dist/templates/common/bundled-skills/atw-meta/references/customize-local/change-hooks.md +57 -0
  419. package/dist/templates/common/bundled-skills/atw-meta/references/customize-local/change-skills-or-commands.md +123 -0
  420. package/dist/templates/common/bundled-skills/atw-meta/references/customize-local/change-spec-structure.md +83 -0
  421. package/dist/templates/common/bundled-skills/atw-meta/references/customize-local/change-task-lifecycle.md +91 -0
  422. package/dist/templates/common/bundled-skills/atw-meta/references/customize-local/change-workflow.md +59 -0
  423. package/dist/templates/common/bundled-skills/atw-meta/references/customize-local/overview.md +55 -0
  424. package/dist/templates/common/bundled-skills/atw-meta/references/local-architecture/bundled-skills.md +159 -0
  425. package/dist/templates/common/bundled-skills/atw-meta/references/local-architecture/context-injection.md +68 -0
  426. package/dist/templates/common/bundled-skills/atw-meta/references/local-architecture/generated-files.md +80 -0
  427. package/dist/templates/common/bundled-skills/atw-meta/references/local-architecture/multi-agent-channel.md +69 -0
  428. package/dist/templates/common/bundled-skills/atw-meta/references/local-architecture/overview.md +51 -0
  429. package/dist/templates/common/bundled-skills/atw-meta/references/local-architecture/spec-system.md +102 -0
  430. package/dist/templates/common/bundled-skills/atw-meta/references/local-architecture/task-system.md +126 -0
  431. package/dist/templates/common/bundled-skills/atw-meta/references/local-architecture/workflow.md +79 -0
  432. package/dist/templates/common/bundled-skills/atw-meta/references/local-architecture/workspace-memory.md +71 -0
  433. package/dist/templates/common/bundled-skills/atw-meta/references/platform-files/agents.md +80 -0
  434. package/dist/templates/common/bundled-skills/atw-meta/references/platform-files/hooks-and-settings.md +72 -0
  435. package/dist/templates/common/bundled-skills/atw-meta/references/platform-files/overview.md +59 -0
  436. package/dist/templates/common/bundled-skills/atw-meta/references/platform-files/platform-map.md +112 -0
  437. package/dist/templates/common/bundled-skills/atw-meta/references/platform-files/skills-and-commands.md +86 -0
  438. package/dist/templates/common/bundled-skills/atw-prototype/LOGIC.md +67 -0
  439. package/dist/templates/common/bundled-skills/atw-prototype/SKILL.md +26 -0
  440. package/dist/templates/common/bundled-skills/atw-prototype/UI.md +112 -0
  441. package/dist/templates/common/bundled-skills/atw-prototype/agents/openai.yaml +3 -0
  442. package/dist/templates/common/bundled-skills/atw-research/SKILL.md +14 -0
  443. package/dist/templates/common/bundled-skills/atw-research/agents/openai.yaml +3 -0
  444. package/dist/templates/common/bundled-skills/atw-session-insight/SKILL.md +81 -0
  445. package/dist/templates/common/bundled-skills/atw-session-insight/references/cli-quick-reference.md +65 -0
  446. package/dist/templates/common/bundled-skills/atw-session-insight/references/triggering-patterns.md +93 -0
  447. package/dist/templates/common/bundled-skills/atw-spec/SKILL.md +75 -0
  448. package/dist/templates/common/bundled-skills/atw-spec/agents/openai.yaml +5 -0
  449. package/dist/templates/common/bundled-skills/atw-spec-bootstrap/SKILL.md +41 -0
  450. package/dist/templates/common/bundled-skills/atw-spec-bootstrap/references/mcp-setup.md +90 -0
  451. package/dist/templates/common/bundled-skills/atw-spec-bootstrap/references/repository-analysis.md +59 -0
  452. package/dist/templates/common/bundled-skills/atw-spec-bootstrap/references/spec-task-planning.md +61 -0
  453. package/dist/templates/common/bundled-skills/atw-spec-bootstrap/references/spec-writing.md +70 -0
  454. package/dist/templates/common/bundled-skills/atw-tdd/SKILL.md +38 -0
  455. package/dist/templates/common/bundled-skills/atw-tdd/agents/openai.yaml +3 -0
  456. package/dist/templates/common/bundled-skills/atw-tdd/mocking.md +59 -0
  457. package/dist/templates/common/bundled-skills/atw-tdd/tests.md +77 -0
  458. package/dist/templates/common/bundled-skills/atw-tickets/SKILL.md +105 -0
  459. package/dist/templates/common/bundled-skills/atw-tickets/agents/openai.yaml +5 -0
  460. package/dist/templates/common/bundled-skills/atw-triage/AGENT-BRIEF.md +207 -0
  461. package/dist/templates/common/bundled-skills/atw-triage/OUT-OF-SCOPE.md +105 -0
  462. package/dist/templates/common/bundled-skills/atw-triage/SKILL.md +112 -0
  463. package/dist/templates/common/bundled-skills/atw-triage/agents/openai.yaml +5 -0
  464. package/dist/templates/common/commands/continue.md +55 -0
  465. package/dist/templates/common/commands/finish-work.md +69 -0
  466. package/dist/templates/common/commands/start.md +68 -0
  467. package/dist/templates/common/index.d.ts +48 -0
  468. package/dist/templates/common/index.d.ts.map +1 -0
  469. package/dist/templates/common/index.js +104 -0
  470. package/dist/templates/common/index.js.map +1 -0
  471. package/dist/templates/common/skills/before-dev.md +44 -0
  472. package/dist/templates/common/skills/brainstorm.md +194 -0
  473. package/dist/templates/common/skills/update-spec.md +351 -0
  474. package/dist/templates/copilot/copilot-instructions.md +11 -0
  475. package/dist/templates/copilot/hooks/session-start.py +510 -0
  476. package/dist/templates/copilot/hooks.json +19 -0
  477. package/dist/templates/copilot/index.d.ts +23 -0
  478. package/dist/templates/copilot/index.d.ts.map +1 -0
  479. package/dist/templates/copilot/index.js +48 -0
  480. package/dist/templates/copilot/index.js.map +1 -0
  481. package/dist/templates/cursor/agents/atw-implement-agent.md +106 -0
  482. package/dist/templates/cursor/agents/atw-review.md +112 -0
  483. package/dist/templates/cursor/hooks.json +24 -0
  484. package/dist/templates/cursor/index.d.ts +13 -0
  485. package/dist/templates/cursor/index.d.ts.map +1 -0
  486. package/dist/templates/cursor/index.js +13 -0
  487. package/dist/templates/cursor/index.js.map +1 -0
  488. package/dist/templates/droid/droids/atw-implement-agent.md +99 -0
  489. package/dist/templates/droid/droids/atw-review.md +105 -0
  490. package/dist/templates/droid/index.d.ts +15 -0
  491. package/dist/templates/droid/index.d.ts.map +1 -0
  492. package/dist/templates/droid/index.js +15 -0
  493. package/dist/templates/droid/index.js.map +1 -0
  494. package/dist/templates/droid/settings.json +69 -0
  495. package/dist/templates/dsh/DSH.md +56 -0
  496. package/dist/templates/dsh/index.d.ts +21 -0
  497. package/dist/templates/dsh/index.d.ts.map +1 -0
  498. package/dist/templates/dsh/index.js +25 -0
  499. package/dist/templates/dsh/index.js.map +1 -0
  500. package/dist/templates/extract.d.ts +40 -0
  501. package/dist/templates/extract.d.ts.map +1 -0
  502. package/dist/templates/extract.js +106 -0
  503. package/dist/templates/extract.js.map +1 -0
  504. package/dist/templates/gemini/agents/atw-implement-agent.md +99 -0
  505. package/dist/templates/gemini/agents/atw-review.md +105 -0
  506. package/dist/templates/gemini/index.d.ts +13 -0
  507. package/dist/templates/gemini/index.d.ts.map +1 -0
  508. package/dist/templates/gemini/index.js +13 -0
  509. package/dist/templates/gemini/index.js.map +1 -0
  510. package/dist/templates/gemini/settings.json +40 -0
  511. package/dist/templates/grok/agents/atw-implement-agent.md +115 -0
  512. package/dist/templates/grok/agents/atw-review.md +105 -0
  513. package/dist/templates/grok/index.d.ts +15 -0
  514. package/dist/templates/grok/index.d.ts.map +1 -0
  515. package/dist/templates/grok/index.js +18 -0
  516. package/dist/templates/grok/index.js.map +1 -0
  517. package/dist/templates/kimi/agents/atw-implement-agent.md +114 -0
  518. package/dist/templates/kimi/agents/atw-review.md +103 -0
  519. package/dist/templates/kimi/index.d.ts +20 -0
  520. package/dist/templates/kimi/index.d.ts.map +1 -0
  521. package/dist/templates/kimi/index.js +23 -0
  522. package/dist/templates/kimi/index.js.map +1 -0
  523. package/dist/templates/kiro/agents/atw-implement-agent.json +26 -0
  524. package/dist/templates/kiro/agents/atw-review.json +26 -0
  525. package/dist/templates/kiro/agents/atw.json +34 -0
  526. package/dist/templates/kiro/hooks/atw-workflow-state.kiro.hook +14 -0
  527. package/dist/templates/kiro/index.d.ts +32 -0
  528. package/dist/templates/kiro/index.d.ts.map +1 -0
  529. package/dist/templates/kiro/index.js +28 -0
  530. package/dist/templates/kiro/index.js.map +1 -0
  531. package/dist/templates/markdown/agents.md +21 -0
  532. package/dist/templates/markdown/gitignore.txt +15 -0
  533. package/dist/templates/markdown/index.d.ts +27 -0
  534. package/dist/templates/markdown/index.d.ts.map +1 -0
  535. package/dist/templates/markdown/index.js +52 -0
  536. package/dist/templates/markdown/index.js.map +1 -0
  537. package/dist/templates/markdown/spec/backend/database-guidelines.md.txt +51 -0
  538. package/dist/templates/markdown/spec/backend/directory-structure.md.txt +54 -0
  539. package/dist/templates/markdown/spec/backend/error-handling.md.txt +51 -0
  540. package/dist/templates/markdown/spec/backend/index.md.txt +38 -0
  541. package/dist/templates/markdown/spec/backend/logging-guidelines.md.txt +51 -0
  542. package/dist/templates/markdown/spec/backend/quality-guidelines.md.txt +51 -0
  543. package/dist/templates/markdown/spec/frontend/component-guidelines.md.txt +59 -0
  544. package/dist/templates/markdown/spec/frontend/directory-structure.md.txt +54 -0
  545. package/dist/templates/markdown/spec/frontend/hook-guidelines.md.txt +51 -0
  546. package/dist/templates/markdown/spec/frontend/index.md.txt +39 -0
  547. package/dist/templates/markdown/spec/frontend/quality-guidelines.md.txt +51 -0
  548. package/dist/templates/markdown/spec/frontend/state-management.md.txt +51 -0
  549. package/dist/templates/markdown/spec/frontend/type-safety.md.txt +51 -0
  550. package/dist/templates/markdown/spec/guides/code-reuse-thinking-guide.md.txt +223 -0
  551. package/dist/templates/markdown/spec/guides/cross-layer-thinking-guide.md.txt +290 -0
  552. package/dist/templates/markdown/spec/guides/cross-platform-thinking-guide.md.txt +634 -0
  553. package/dist/templates/markdown/spec/guides/index.md.txt +97 -0
  554. package/dist/templates/markdown/workspace-index.md +125 -0
  555. package/dist/templates/markdown/worktree.yaml.txt +58 -0
  556. package/dist/templates/omp/agents/atw-implement-agent.md +45 -0
  557. package/dist/templates/omp/agents/atw-review.md +41 -0
  558. package/dist/templates/omp/extensions/atw/index.ts.txt +1109 -0
  559. package/dist/templates/omp/index.d.ts +4 -0
  560. package/dist/templates/omp/index.d.ts.map +1 -0
  561. package/dist/templates/omp/index.js +9 -0
  562. package/dist/templates/omp/index.js.map +1 -0
  563. package/dist/templates/opencode/agents/atw-implement-agent.md +115 -0
  564. package/dist/templates/opencode/agents/atw-review.md +120 -0
  565. package/dist/templates/opencode/lib/atw-context.js +637 -0
  566. package/dist/templates/opencode/lib/context-visibility.js +148 -0
  567. package/dist/templates/opencode/lib/session-utils.js +474 -0
  568. package/dist/templates/opencode/package.json +6 -0
  569. package/dist/templates/opencode/plugins/inject-subagent-context.js +390 -0
  570. package/dist/templates/opencode/plugins/inject-workflow-state.js +240 -0
  571. package/dist/templates/opencode/plugins/session-start.js +65 -0
  572. package/dist/templates/pi/agents/atw-implement-agent.md +42 -0
  573. package/dist/templates/pi/agents/atw-review.md +37 -0
  574. package/dist/templates/pi/extensions/atw/index.ts.txt +2014 -0
  575. package/dist/templates/pi/index.d.ts +5 -0
  576. package/dist/templates/pi/index.d.ts.map +1 -0
  577. package/dist/templates/pi/index.js +12 -0
  578. package/dist/templates/pi/index.js.map +1 -0
  579. package/dist/templates/pi/settings.json +9 -0
  580. package/dist/templates/qoder/agents/atw-implement-agent.md +100 -0
  581. package/dist/templates/qoder/agents/atw-review.md +106 -0
  582. package/dist/templates/qoder/index.d.ts +15 -0
  583. package/dist/templates/qoder/index.d.ts.map +1 -0
  584. package/dist/templates/qoder/index.js +15 -0
  585. package/dist/templates/qoder/index.js.map +1 -0
  586. package/dist/templates/qoder/settings.json +59 -0
  587. package/dist/templates/reasonix/agents/atw-implement-agent.md +41 -0
  588. package/dist/templates/reasonix/agents/atw-review.md +36 -0
  589. package/dist/templates/reasonix/index.d.ts +13 -0
  590. package/dist/templates/reasonix/index.d.ts.map +1 -0
  591. package/dist/templates/reasonix/index.js +16 -0
  592. package/dist/templates/reasonix/index.js.map +1 -0
  593. package/dist/templates/shared-hooks/index.d.ts +77 -0
  594. package/dist/templates/shared-hooks/index.d.ts.map +1 -0
  595. package/dist/templates/shared-hooks/index.js +140 -0
  596. package/dist/templates/shared-hooks/index.js.map +1 -0
  597. package/dist/templates/shared-hooks/inject-shell-session-context.py +292 -0
  598. package/dist/templates/shared-hooks/inject-subagent-context.py +1178 -0
  599. package/dist/templates/shared-hooks/inject-workflow-state.py +488 -0
  600. package/dist/templates/shared-hooks/session-start.py +889 -0
  601. package/dist/templates/snow/SNOW.md +86 -0
  602. package/dist/templates/snow/agents/atw-implement-agent.md +152 -0
  603. package/dist/templates/snow/agents/atw-review.md +135 -0
  604. package/dist/templates/snow/hooks/beforeSubAgentStart.json +15 -0
  605. package/dist/templates/snow/hooks/onSessionStart.json +15 -0
  606. package/dist/templates/snow/hooks/onUserMessage.json +15 -0
  607. package/dist/templates/snow/hooks/write-atw-context.py +637 -0
  608. package/dist/templates/snow/index.d.ts +25 -0
  609. package/dist/templates/snow/index.d.ts.map +1 -0
  610. package/dist/templates/snow/index.js +35 -0
  611. package/dist/templates/snow/index.js.map +1 -0
  612. package/dist/templates/template-utils.d.ts +26 -0
  613. package/dist/templates/template-utils.d.ts.map +1 -0
  614. package/dist/templates/template-utils.js +64 -0
  615. package/dist/templates/template-utils.js.map +1 -0
  616. package/dist/templates/trae/agents/atw-implement-agent.md +100 -0
  617. package/dist/templates/trae/agents/atw-review.md +106 -0
  618. package/dist/templates/trae/hooks.json +39 -0
  619. package/dist/templates/trae/index.d.ts +15 -0
  620. package/dist/templates/trae/index.d.ts.map +1 -0
  621. package/dist/templates/trae/index.js +15 -0
  622. package/dist/templates/trae/index.js.map +1 -0
  623. package/dist/templates/zcode/agents/atw-implement-agent.md +108 -0
  624. package/dist/templates/zcode/agents/atw-review.md +109 -0
  625. package/dist/templates/zcode/config.json +52 -0
  626. package/dist/templates/zcode/index.d.ts +22 -0
  627. package/dist/templates/zcode/index.d.ts.map +1 -0
  628. package/dist/templates/zcode/index.js +26 -0
  629. package/dist/templates/zcode/index.js.map +1 -0
  630. package/dist/types/ai-tools.d.ts +95 -0
  631. package/dist/types/ai-tools.d.ts.map +1 -0
  632. package/dist/types/ai-tools.js +494 -0
  633. package/dist/types/ai-tools.js.map +1 -0
  634. package/dist/types/migration.d.ts +125 -0
  635. package/dist/types/migration.d.ts.map +1 -0
  636. package/dist/types/migration.js +8 -0
  637. package/dist/types/migration.js.map +1 -0
  638. package/dist/utils/ablation-store.d.ts +123 -0
  639. package/dist/utils/ablation-store.d.ts.map +1 -0
  640. package/dist/utils/ablation-store.js +749 -0
  641. package/dist/utils/ablation-store.js.map +1 -0
  642. package/dist/utils/agent-refs.d.ts +31 -0
  643. package/dist/utils/agent-refs.d.ts.map +1 -0
  644. package/dist/utils/agent-refs.js +63 -0
  645. package/dist/utils/agent-refs.js.map +1 -0
  646. package/dist/utils/atomic-write.d.ts +12 -0
  647. package/dist/utils/atomic-write.d.ts.map +1 -0
  648. package/dist/utils/atomic-write.js +30 -0
  649. package/dist/utils/atomic-write.js.map +1 -0
  650. package/dist/utils/compare-versions.d.ts +12 -0
  651. package/dist/utils/compare-versions.d.ts.map +1 -0
  652. package/dist/utils/compare-versions.js +86 -0
  653. package/dist/utils/compare-versions.js.map +1 -0
  654. package/dist/utils/cwd-guard.d.ts +38 -0
  655. package/dist/utils/cwd-guard.d.ts.map +1 -0
  656. package/dist/utils/cwd-guard.js +62 -0
  657. package/dist/utils/cwd-guard.js.map +1 -0
  658. package/dist/utils/file-writer.d.ts +36 -0
  659. package/dist/utils/file-writer.d.ts.map +1 -0
  660. package/dist/utils/file-writer.js +204 -0
  661. package/dist/utils/file-writer.js.map +1 -0
  662. package/dist/utils/managed-paths.d.ts +5 -0
  663. package/dist/utils/managed-paths.d.ts.map +1 -0
  664. package/dist/utils/managed-paths.js +51 -0
  665. package/dist/utils/managed-paths.js.map +1 -0
  666. package/dist/utils/managed-removal.d.ts +74 -0
  667. package/dist/utils/managed-removal.d.ts.map +1 -0
  668. package/dist/utils/managed-removal.js +270 -0
  669. package/dist/utils/managed-removal.js.map +1 -0
  670. package/dist/utils/manifest-prune.d.ts +61 -0
  671. package/dist/utils/manifest-prune.d.ts.map +1 -0
  672. package/dist/utils/manifest-prune.js +135 -0
  673. package/dist/utils/manifest-prune.js.map +1 -0
  674. package/dist/utils/posix.d.ts +13 -0
  675. package/dist/utils/posix.d.ts.map +1 -0
  676. package/dist/utils/posix.js +15 -0
  677. package/dist/utils/posix.js.map +1 -0
  678. package/dist/utils/project-detector.d.ts +46 -0
  679. package/dist/utils/project-detector.d.ts.map +1 -0
  680. package/dist/utils/project-detector.js +666 -0
  681. package/dist/utils/project-detector.js.map +1 -0
  682. package/dist/utils/proxy.d.ts +25 -0
  683. package/dist/utils/proxy.d.ts.map +1 -0
  684. package/dist/utils/proxy.js +60 -0
  685. package/dist/utils/proxy.js.map +1 -0
  686. package/dist/utils/registry-config.d.ts +7 -0
  687. package/dist/utils/registry-config.d.ts.map +1 -0
  688. package/dist/utils/registry-config.js +172 -0
  689. package/dist/utils/registry-config.js.map +1 -0
  690. package/dist/utils/task-json.d.ts +13 -0
  691. package/dist/utils/task-json.d.ts.map +1 -0
  692. package/dist/utils/task-json.js +12 -0
  693. package/dist/utils/task-json.js.map +1 -0
  694. package/dist/utils/template-fetcher.d.ts +161 -0
  695. package/dist/utils/template-fetcher.d.ts.map +1 -0
  696. package/dist/utils/template-fetcher.js +994 -0
  697. package/dist/utils/template-fetcher.js.map +1 -0
  698. package/dist/utils/template-hash.d.ts +127 -0
  699. package/dist/utils/template-hash.d.ts.map +1 -0
  700. package/dist/utils/template-hash.js +335 -0
  701. package/dist/utils/template-hash.js.map +1 -0
  702. package/dist/utils/uninstall-scrubbers.d.ts +66 -0
  703. package/dist/utils/uninstall-scrubbers.d.ts.map +1 -0
  704. package/dist/utils/uninstall-scrubbers.js +417 -0
  705. package/dist/utils/uninstall-scrubbers.js.map +1 -0
  706. package/dist/utils/workflow-resolver.d.ts +86 -0
  707. package/dist/utils/workflow-resolver.d.ts.map +1 -0
  708. package/dist/utils/workflow-resolver.js +265 -0
  709. package/dist/utils/workflow-resolver.js.map +1 -0
  710. package/package.json +93 -0
@@ -0,0 +1,2255 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import chalk from "chalk";
5
+ import inquirer from "inquirer";
6
+ import { DIR_NAMES, FILE_NAMES, PATHS } from "../constants/paths.js";
7
+ import { VERSION, PACKAGE_NAME } from "../constants/version.js";
8
+ import { getMigrationsForVersion, getAllMigrations, getMigrationMetadata, getConfigSectionsAddedBetween, } from "../migrations/index.js";
9
+ import { loadHashes, saveHashes, updateHashes, isTemplateModified, removeHash, renameHash, computeHash, shouldExcludeFromHash, } from "../utils/template-hash.js";
10
+ import { compareVersions } from "../utils/compare-versions.js";
11
+ import { toPosix } from "../utils/posix.js";
12
+ import { setupProxy } from "../utils/proxy.js";
13
+ import { emptyTaskJson } from "../utils/task-json.js";
14
+ // Import templates for comparison
15
+ import { getAllScripts, getAllAgents,
16
+ // Configuration
17
+ configYamlTemplate, gitignoreTemplate, workflowMdTemplate, } from "../templates/atw/index.js";
18
+ import { agentsMdContent } from "../templates/markdown/index.js";
19
+ import { COPILOT_INSTRUCTIONS_BLOCK_END, COPILOT_INSTRUCTIONS_BLOCK_START, COPILOT_INSTRUCTIONS_PATH, getCopilotInstructions, } from "../templates/copilot/index.js";
20
+ import { ALL_MANAGED_DIRS, getConfiguredPlatforms, collectPlatformTemplates, } from "../configurators/index.js";
21
+ import { replacePythonCommandLiterals } from "../configurators/shared.js";
22
+ import { preserveCodexAgentModelKeys } from "../configurators/codex.js";
23
+ import { ensureGitattributes } from "../configurators/workflow.js";
24
+ import { pruneOrphanManifestKeys } from "../utils/manifest-prune.js";
25
+ import { fetchRegistrySpecTemplates, collectDirectoryFiles, removeDirectory, parseRegistrySource, probeRegistryIndex, downloadTemplateById, } from "../utils/template-fetcher.js";
26
+ import { loadSpecRegistryConfig } from "../utils/registry-config.js";
27
+ import { cleanupEmptyDirs, ATW_BLOCK_END, ATW_BLOCK_START, } from "../utils/managed-paths.js";
28
+ export { cleanupEmptyDirs, ATW_BLOCK_END, ATW_BLOCK_START, } from "../utils/managed-paths.js";
29
+ const CLAUDE_SETTINGS_PATH = ".claude/settings.json";
30
+ const LEGACY_UNTRACKED_AGENTS_MD_BLOCK_HASHES = new Set([
31
+ // Older installs wrote AGENTS.md without hash-tracking it.
32
+ // This hash is the pristine ATW-managed block before the Subagents
33
+ // section was added, so old untouched projects can be updated without a
34
+ // false "modified by you" conflict.
35
+ "c1f511b1cfc1902f2147da159f09cc51f380b0c9e341cdb3ac5dea5233f3e307",
36
+ ]);
37
+ // Paths that should never be touched (true user data)
38
+ // spec/ is user-customized content created during init; update should never modify it
39
+ const PROTECTED_PATHS = [
40
+ `${DIR_NAMES.WORKFLOW}/${DIR_NAMES.WORKSPACE}`, // workspace/
41
+ `${DIR_NAMES.WORKFLOW}/${DIR_NAMES.TASKS}`, // tasks/
42
+ `${DIR_NAMES.WORKFLOW}/${DIR_NAMES.SPEC}`, // spec/
43
+ `${DIR_NAMES.WORKFLOW}/.developer`,
44
+ `${DIR_NAMES.WORKFLOW}/.current-task`,
45
+ ];
46
+ function getManagedBlock(content, startMarker, endMarker) {
47
+ const start = content.indexOf(startMarker);
48
+ if (start === -1) {
49
+ return null;
50
+ }
51
+ const end = content.indexOf(endMarker, start);
52
+ if (end === -1) {
53
+ return null;
54
+ }
55
+ return content.slice(start, end + endMarker.length);
56
+ }
57
+ function getAtwManagedBlock(content) {
58
+ return getManagedBlock(content, ATW_BLOCK_START, ATW_BLOCK_END);
59
+ }
60
+ function replaceManagedBlock(existingContent, templateContent, startMarker, endMarker) {
61
+ const existingStart = existingContent.indexOf(startMarker);
62
+ if (existingStart === -1) {
63
+ return null;
64
+ }
65
+ const existingEnd = existingContent.indexOf(endMarker, existingStart);
66
+ if (existingEnd === -1) {
67
+ return null;
68
+ }
69
+ const templateBlock = getManagedBlock(templateContent, startMarker, endMarker);
70
+ if (!templateBlock) {
71
+ return null;
72
+ }
73
+ return (existingContent.slice(0, existingStart) +
74
+ templateBlock +
75
+ existingContent.slice(existingEnd + endMarker.length));
76
+ }
77
+ function mergeManagedBlockContent(existingContent, templateContent, startMarker, endMarker) {
78
+ const replaced = replaceManagedBlock(existingContent, templateContent, startMarker, endMarker);
79
+ if (replaced !== null) {
80
+ return replaced;
81
+ }
82
+ const templateBlock = getManagedBlock(templateContent, startMarker, endMarker);
83
+ if (!templateBlock) {
84
+ return templateContent;
85
+ }
86
+ const trimmed = existingContent.replace(/\s+$/, "");
87
+ return `${trimmed}\n\n${templateBlock}\n`;
88
+ }
89
+ function buildManagedBlockTemplate(cwd, relativePath, templateContent, startMarker, endMarker) {
90
+ const fullPath = path.join(cwd, ...relativePath.split("/"));
91
+ if (!fs.existsSync(fullPath)) {
92
+ return templateContent;
93
+ }
94
+ const existingContent = fs.readFileSync(fullPath, "utf-8");
95
+ return mergeManagedBlockContent(existingContent, templateContent, startMarker, endMarker);
96
+ }
97
+ function buildAgentsMdTemplate(cwd) {
98
+ return buildManagedBlockTemplate(cwd, FILE_NAMES.AGENTS, agentsMdContent, ATW_BLOCK_START, ATW_BLOCK_END);
99
+ }
100
+ function buildCopilotInstructionsTemplate(cwd) {
101
+ return buildManagedBlockTemplate(cwd, COPILOT_INSTRUCTIONS_PATH, getCopilotInstructions(), COPILOT_INSTRUCTIONS_BLOCK_START, COPILOT_INSTRUCTIONS_BLOCK_END);
102
+ }
103
+ function isKnownUntrackedTemplate(relativePath, existingContent) {
104
+ if (relativePath !== FILE_NAMES.AGENTS) {
105
+ return false;
106
+ }
107
+ const managedBlock = getAtwManagedBlock(existingContent);
108
+ if (!managedBlock) {
109
+ return false;
110
+ }
111
+ return LEGACY_UNTRACKED_AGENTS_MD_BLOCK_HASHES.has(computeHash(managedBlock));
112
+ }
113
+ function isSafeUntrackedCopilotInstructionsMerge(relativePath, existingContent, newContent) {
114
+ if (relativePath !== COPILOT_INSTRUCTIONS_PATH) {
115
+ return false;
116
+ }
117
+ if (getManagedBlock(existingContent, COPILOT_INSTRUCTIONS_BLOCK_START, COPILOT_INSTRUCTIONS_BLOCK_END)) {
118
+ return false;
119
+ }
120
+ return (mergeManagedBlockContent(existingContent, getCopilotInstructions(), COPILOT_INSTRUCTIONS_BLOCK_START, COPILOT_INSTRUCTIONS_BLOCK_END) === newContent);
121
+ }
122
+ /**
123
+ * Check if a path is blocked by PROTECTED_PATHS
124
+ */
125
+ function isProtectedPath(filePath) {
126
+ return PROTECTED_PATHS.some((pp) => filePath === pp || filePath.startsWith(pp.endsWith("/") ? pp : pp + "/"));
127
+ }
128
+ /**
129
+ * Collect and classify safe-file-delete migrations
130
+ *
131
+ * safe-file-delete auto-executes (no --migrate needed) when:
132
+ * - File exists
133
+ * - Content hash matches allowed_hashes
134
+ * - Path is not protected or in update.skip
135
+ * - Path is not owned by the current template set
136
+ */
137
+ function collectSafeFileDeletes(migrations, cwd, skipPaths, currentTemplatePaths,
138
+ /**
139
+ * Bypass `update.skip` for safe-file-delete. Enable this for breaking releases
140
+ * where honoring skip would leave the project half-migrated (old files at
141
+ * protected paths sitting next to the new architecture forever). The hash
142
+ * check in `allowed_hashes` is still the ultimate safety net — user-modified
143
+ * files still stay put with a "skip-modified" warning.
144
+ */
145
+ bypassUpdateSkip = false) {
146
+ // Historical migrations are loaded forever, so current template ownership
147
+ // must win when a later release intentionally restores a retired path.
148
+ const safeDeletes = migrations.filter((m) => m.type === "safe-file-delete" && !currentTemplatePaths.has(m.from));
149
+ const results = [];
150
+ for (const item of safeDeletes) {
151
+ const fullPath = path.join(cwd, item.from);
152
+ // Check: file exists?
153
+ if (!fs.existsSync(fullPath)) {
154
+ results.push({ item, action: "skip-missing" });
155
+ continue;
156
+ }
157
+ // Check: protected path? (user data dirs — always protected, never bypassed)
158
+ if (isProtectedPath(item.from)) {
159
+ results.push({ item, action: "skip-protected" });
160
+ continue;
161
+ }
162
+ // Check: update.skip? (can be bypassed for breaking releases)
163
+ if (!bypassUpdateSkip &&
164
+ skipPaths.some((skip) => item.from === skip ||
165
+ item.from.startsWith(skip.endsWith("/") ? skip : skip + "/"))) {
166
+ results.push({ item, action: "skip-update-skip" });
167
+ continue;
168
+ }
169
+ // Check: hash matches allowed_hashes?
170
+ if (!item.allowed_hashes || item.allowed_hashes.length === 0) {
171
+ // No allowed hashes defined — skip for safety
172
+ results.push({ item, action: "skip-modified" });
173
+ continue;
174
+ }
175
+ try {
176
+ const content = fs.readFileSync(fullPath, "utf-8");
177
+ const fileHash = computeHash(content);
178
+ if (item.allowed_hashes.includes(fileHash)) {
179
+ results.push({ item, action: "delete" });
180
+ }
181
+ else {
182
+ results.push({ item, action: "skip-modified" });
183
+ }
184
+ }
185
+ catch {
186
+ results.push({ item, action: "skip-missing" });
187
+ }
188
+ }
189
+ return results;
190
+ }
191
+ /**
192
+ * Print safe-file-delete summary
193
+ */
194
+ function printSafeFileDeleteSummary(classified) {
195
+ const toDelete = classified.filter((c) => c.action === "delete");
196
+ const modified = classified.filter((c) => c.action === "skip-modified");
197
+ const updateSkip = classified.filter((c) => c.action === "skip-update-skip");
198
+ if (toDelete.length === 0 &&
199
+ modified.length === 0 &&
200
+ updateSkip.length === 0) {
201
+ return;
202
+ }
203
+ console.log(chalk.cyan(" Deprecated commands cleanup:"));
204
+ if (toDelete.length > 0) {
205
+ for (const c of toDelete) {
206
+ console.log(chalk.green(` āœ• ${c.item.from}${c.item.description ? ` (${c.item.description})` : ""}`));
207
+ }
208
+ }
209
+ if (modified.length > 0) {
210
+ for (const c of modified) {
211
+ console.log(chalk.yellow(` ? ${c.item.from} (modified, skipped)`));
212
+ }
213
+ }
214
+ if (updateSkip.length > 0) {
215
+ for (const c of updateSkip) {
216
+ console.log(chalk.gray(` ā—‹ ${c.item.from} (skipped, update.skip)`));
217
+ }
218
+ }
219
+ console.log("");
220
+ }
221
+ /**
222
+ * Execute safe-file-delete items (delete files + clean up empty dirs)
223
+ */
224
+ function executeSafeFileDeletes(classified, cwd) {
225
+ const toDelete = classified.filter((c) => c.action === "delete");
226
+ let deleted = 0;
227
+ for (const c of toDelete) {
228
+ const fullPath = path.join(cwd, c.item.from);
229
+ try {
230
+ fs.unlinkSync(fullPath);
231
+ removeHash(cwd, c.item.from);
232
+ cleanupEmptyDirs(cwd, path.dirname(c.item.from));
233
+ deleted++;
234
+ }
235
+ catch {
236
+ // File may have been removed between classify and execute
237
+ }
238
+ }
239
+ return deleted;
240
+ }
241
+ /**
242
+ * Load update.skip paths from .atw/config.yaml
243
+ *
244
+ * Parses simple YAML structure:
245
+ * update:
246
+ * skip:
247
+ * - path1
248
+ * - path2
249
+ *
250
+ * @internal Exported for testing only
251
+ */
252
+ export function loadUpdateSkipPaths(cwd) {
253
+ const configPath = path.join(cwd, DIR_NAMES.WORKFLOW, "config.yaml");
254
+ if (!fs.existsSync(configPath))
255
+ return [];
256
+ try {
257
+ const content = fs.readFileSync(configPath, "utf-8");
258
+ const lines = content.split("\n");
259
+ const paths = [];
260
+ let inUpdate = false;
261
+ let inSkip = false;
262
+ for (const line of lines) {
263
+ const trimmed = line.trimEnd();
264
+ // Check for "update:" section (no indentation or at root level)
265
+ if (/^update:\s*$/.test(trimmed)) {
266
+ inUpdate = true;
267
+ inSkip = false;
268
+ continue;
269
+ }
270
+ // Check for "skip:" under update (indented)
271
+ if (inUpdate && /^\s+skip:\s*$/.test(trimmed)) {
272
+ inSkip = true;
273
+ continue;
274
+ }
275
+ // Collect list items under skip
276
+ if (inSkip) {
277
+ const match = trimmed.match(/^\s+-\s+(.+)$/);
278
+ if (match) {
279
+ paths.push(match[1].trim().replace(/^['"]|['"]$/g, ""));
280
+ continue;
281
+ }
282
+ // If line is non-empty and not a list item, we've left the skip section
283
+ if (trimmed !== "" && !trimmed.startsWith("#")) {
284
+ inSkip = false;
285
+ inUpdate = false;
286
+ }
287
+ }
288
+ // If we're in update but hit a non-indented line, we've left the update section
289
+ if (inUpdate &&
290
+ trimmed !== "" &&
291
+ !trimmed.startsWith(" ") &&
292
+ !trimmed.startsWith("#")) {
293
+ inUpdate = false;
294
+ inSkip = false;
295
+ }
296
+ }
297
+ return paths;
298
+ }
299
+ catch {
300
+ // Config exists but failed to parse — warn user that skip rules won't apply
301
+ console.warn(`Warning: failed to parse ${configPath}, update.skip rules will not be applied`);
302
+ return [];
303
+ }
304
+ }
305
+ /**
306
+ * Extract a "section" from a config.yaml-style template by sectionHeading.
307
+ *
308
+ * A section is delimited by `#---...---` separator lines (the same pattern
309
+ * used in the bundled `config.yaml` template). The first line inside the
310
+ * separator block whose `# ` content matches `sectionHeading` identifies the
311
+ * section; the section spans from that opening separator block through the
312
+ * line preceding the next `#---` separator block (or EOF).
313
+ *
314
+ * Returns the extracted text including its leading separator block, or `null`
315
+ * when no matching section is found.
316
+ *
317
+ * @internal Exported for testing only.
318
+ */
319
+ export function extractConfigSection(template, sectionHeading) {
320
+ const lines = template.split("\n");
321
+ const isSeparator = (line) => /^#-{3,}\s*$/.test(line.trimEnd());
322
+ for (let i = 0; i < lines.length; i++) {
323
+ if (!isSeparator(lines[i]))
324
+ continue;
325
+ // Look ahead for `# <heading>` then another separator that closes the
326
+ // heading block.
327
+ const headingLine = lines[i + 1];
328
+ const closingSeparator = lines[i + 2];
329
+ if (headingLine === undefined || closingSeparator === undefined)
330
+ continue;
331
+ if (!headingLine.startsWith("# "))
332
+ continue;
333
+ if (!isSeparator(closingSeparator))
334
+ continue;
335
+ if (headingLine.slice(2).trim() !== sectionHeading)
336
+ continue;
337
+ // Section starts at i; find the next separator block to bound it.
338
+ let end = lines.length;
339
+ for (let j = i + 3; j < lines.length; j++) {
340
+ if (isSeparator(lines[j])) {
341
+ end = j;
342
+ break;
343
+ }
344
+ }
345
+ return lines.slice(i, end).join("\n").replace(/\n+$/, "");
346
+ }
347
+ return null;
348
+ }
349
+ /**
350
+ * Apply additive config.yaml sections introduced between two versions.
351
+ *
352
+ * Walks the supplied entries, dedupes by `file+sentinel`, and for each unique
353
+ * entry: if the user file exists and lacks the sentinel, extracts the named
354
+ * section from `templateContent` and appends it. Idempotent — re-running the
355
+ * step on a file that already contains the sentinel is a no-op.
356
+ *
357
+ * @internal Exported for testing only.
358
+ */
359
+ export function applyConfigSectionsAdded(entries, cwd, bundledTemplates) {
360
+ const seen = new Set();
361
+ let appended = 0;
362
+ for (const entry of entries) {
363
+ const dedupeKey = `${entry.file}::${entry.sentinel}`;
364
+ if (seen.has(dedupeKey))
365
+ continue;
366
+ seen.add(dedupeKey);
367
+ const targetPath = path.join(cwd, entry.file);
368
+ if (!fs.existsSync(targetPath))
369
+ continue;
370
+ let userContent;
371
+ try {
372
+ userContent = fs.readFileSync(targetPath, "utf-8");
373
+ }
374
+ catch {
375
+ continue;
376
+ }
377
+ if (userContent.includes(entry.sentinel))
378
+ continue;
379
+ const template = bundledTemplates.get(entry.file);
380
+ if (!template)
381
+ continue;
382
+ const section = extractConfigSection(template, entry.sectionHeading);
383
+ if (!section)
384
+ continue;
385
+ const separator = userContent.endsWith("\n") ? "\n" : "\n\n";
386
+ const newContent = userContent + separator + section + "\n";
387
+ try {
388
+ fs.writeFileSync(targetPath, newContent);
389
+ }
390
+ catch {
391
+ continue;
392
+ }
393
+ console.log(chalk.green(` + Added config section "${entry.sectionHeading}" to ${entry.file}`));
394
+ appended++;
395
+ }
396
+ return { appended };
397
+ }
398
+ /**
399
+ * Collect all template files that should be managed by update
400
+ * Only collects templates for platforms that are already configured (have directories)
401
+ */
402
+ /**
403
+ * Detect if legacy Codex upgrade is needed.
404
+ *
405
+ * Old ATW versions used `.agents/skills/` as codex's configDir.
406
+ * New versions use `.codex/` for Codex-specific config and `.agents/skills/`
407
+ * as a shared layer.
408
+ *
409
+ * Detection: ATW-tracked hashes contain `.agents/skills/` entries
410
+ * but `.codex/` does not exist. This avoids misclassifying repos that
411
+ * have `.agents/skills/` from other tools (Kimi CLI, Amp, etc.).
412
+ *
413
+ * Returns true if upgrade is needed. Does NOT perform the upgrade —
414
+ * caller should run configurePlatform("codex") after backup/confirm.
415
+ */
416
+ function needsCodexUpgrade(cwd) {
417
+ if (fs.existsSync(path.join(cwd, ".codex"))) {
418
+ return false;
419
+ }
420
+ // Legacy Codex marker: old Codex installs tracked command-as-skill files
421
+ // under `.agents/skills/` before `.codex/` existed as a separate config dir.
422
+ // A current or future non-Codex platform may own those paths too, so do not
423
+ // trigger the Codex backfill when a configured non-Codex platform declares
424
+ // the marker paths in its templates.
425
+ const hashes = loadHashes(cwd);
426
+ const legacyMarkers = [
427
+ ".agents/skills/atw-continue/SKILL.md",
428
+ ".agents/skills/atw-finish-work/SKILL.md",
429
+ ];
430
+ const hasLegacyMarker = legacyMarkers.some((key) => hashes[key] !== undefined);
431
+ if (!hasLegacyMarker) {
432
+ return false;
433
+ }
434
+ for (const platformId of getConfiguredPlatforms(cwd)) {
435
+ if (platformId === "codex") {
436
+ continue;
437
+ }
438
+ const platformFiles = collectPlatformTemplates(platformId);
439
+ if (platformFiles && legacyMarkers.some((key) => platformFiles.has(key))) {
440
+ return false;
441
+ }
442
+ }
443
+ return true;
444
+ }
445
+ function preserveExistingClaudeStatusLine(cwd, templates) {
446
+ const newSettingsContent = templates.get(CLAUDE_SETTINGS_PATH);
447
+ if (!newSettingsContent)
448
+ return;
449
+ const settingsPath = path.join(cwd, CLAUDE_SETTINGS_PATH);
450
+ if (!fs.existsSync(settingsPath))
451
+ return;
452
+ try {
453
+ const existingSettings = JSON.parse(fs.readFileSync(settingsPath, "utf-8"));
454
+ if (!Object.prototype.hasOwnProperty.call(existingSettings, "statusLine")) {
455
+ return;
456
+ }
457
+ const newSettings = JSON.parse(newSettingsContent);
458
+ if (Object.prototype.hasOwnProperty.call(newSettings, "statusLine")) {
459
+ return;
460
+ }
461
+ newSettings.statusLine = existingSettings.statusLine;
462
+ templates.set(CLAUDE_SETTINGS_PATH, `${JSON.stringify(newSettings, null, 2)}\n`);
463
+ }
464
+ catch {
465
+ // Invalid local JSON is handled by the normal conflict path.
466
+ }
467
+ }
468
+ /**
469
+ * Carry the user's own top-level `config.yaml` keys across a template rewrite.
470
+ *
471
+ * `config.yaml` is delivered as a whole file, so overwriting it — on `--force`,
472
+ * or when the user picks "overwrite" at the modified-file prompt — replaces
473
+ * every local edit with the template. That is a problem specific to this file,
474
+ * because the template ships its opt-in surface *commented out* and tells the
475
+ * reader to uncomment it: `hooks`, `packages`, `default_package`,
476
+ * `session_auto_commit`, `codex`, `context_injection`, `prompt_injection`.
477
+ * Filling any of them in creates a top-level key the template does not have,
478
+ * and the next overwrite deletes it.
479
+ *
480
+ * Two of those are not hypothetical. `atw init` writes `packages:` /
481
+ * `default_package:` itself when it detects a monorepo, and `update:` — the
482
+ * `update.skip` list, which exists precisely to tell this command "leave these
483
+ * files alone" — is not in the template at all, so update deletes its own
484
+ * opt-out.
485
+ *
486
+ * `registry:` already had a bespoke rescue ({@link preserveExistingRegistryConfig}).
487
+ * This is the general form of the same problem, so run it *after* that one:
488
+ * the registry block is part of the effective template by then and is not
489
+ * carried twice.
490
+ *
491
+ * @internal Exported for testing only.
492
+ */
493
+ export function preserveLocalConfigKeys(template, existing) {
494
+ const TOP_KEY = /^([A-Za-z_][A-Za-z0-9_-]*):/;
495
+ const templateKeys = new Set();
496
+ for (const line of template.split("\n")) {
497
+ const m = TOP_KEY.exec(line);
498
+ if (m)
499
+ templateKeys.add(m[1]);
500
+ }
501
+ const lines = existing.split("\n");
502
+ const keyAt = [];
503
+ lines.forEach((line, i) => {
504
+ const m = TOP_KEY.exec(line);
505
+ if (m)
506
+ keyAt.push({ key: m[1], line: i });
507
+ });
508
+ // Pull in the comment lines sitting directly above a key. That is where
509
+ // `atw init` puts "# Auto-detected monorepo packages"; dropping it leaves
510
+ // the next reader with a block whose origin is unexplained.
511
+ const startOf = (line) => {
512
+ let start = line;
513
+ while (start > 0 && /^\s*#/.test(lines[start - 1]))
514
+ start--;
515
+ return start;
516
+ };
517
+ const stopOf = (idx) => {
518
+ const line = keyAt[idx].line;
519
+ const next = idx + 1 < keyAt.length ? keyAt[idx + 1].line : null;
520
+ let stop = next ?? lines.length;
521
+ if (next !== null) {
522
+ // Comments immediately above the *next* key belong to that key, not here.
523
+ while (stop > line + 1 && /^\s*#/.test(lines[stop - 1]))
524
+ stop--;
525
+ }
526
+ while (stop > line + 1 && lines[stop - 1].trim() === "")
527
+ stop--;
528
+ return stop;
529
+ };
530
+ const carried = [];
531
+ const chunks = [];
532
+ // Consecutive local keys are copied as one slice, verbatim. Emitting them
533
+ // separately and re-joining would rewrite the blank lines between them, so
534
+ // every update would churn the user's layout for no reason.
535
+ for (let i = 0; i < keyAt.length; i++) {
536
+ if (templateKeys.has(keyAt[i].key))
537
+ continue;
538
+ let end = i;
539
+ while (end + 1 < keyAt.length && !templateKeys.has(keyAt[end + 1].key))
540
+ end++;
541
+ for (let k = i; k <= end; k++)
542
+ carried.push(keyAt[k].key);
543
+ chunks.push(lines.slice(startOf(keyAt[i].line), stopOf(end)).join("\n"));
544
+ i = end;
545
+ }
546
+ if (chunks.length === 0)
547
+ return { merged: template, carried };
548
+ return {
549
+ merged: `${template.trimEnd()}\n\n${chunks.join("\n\n")}\n`,
550
+ carried,
551
+ };
552
+ }
553
+ /** Read the installed config.yaml and merge its local-only keys into `template`. */
554
+ function preserveLocalConfig(cwd, template) {
555
+ const configPath = path.join(cwd, DIR_NAMES.WORKFLOW, "config.yaml");
556
+ let existing;
557
+ try {
558
+ existing = fs.readFileSync(configPath, "utf-8");
559
+ }
560
+ catch {
561
+ return template; // Nothing installed yet — nothing to carry.
562
+ }
563
+ return preserveLocalConfigKeys(template, existing).merged;
564
+ }
565
+ function preserveExistingRegistryConfig(cwd, template) {
566
+ const registry = loadSpecRegistryConfig(cwd);
567
+ if (!registry)
568
+ return template;
569
+ return (template.trimEnd() +
570
+ "\n\n" +
571
+ "#-------------------------------------------------------------------------------\n" +
572
+ "# Registry\n" +
573
+ "#-------------------------------------------------------------------------------\n\n" +
574
+ "# Source used to install .atw/spec. atw update refreshes this\n" +
575
+ "# hash-tracked spec template while preserving local edits through the\n" +
576
+ "# normal update conflict flow.\n" +
577
+ "registry:\n" +
578
+ " spec:\n" +
579
+ ` source: ${registry.source}\n` +
580
+ (registry.template ? ` template: ${registry.template}\n` : ""));
581
+ }
582
+ async function collectRegistrySpecTemplates(cwd) {
583
+ const config = loadSpecRegistryConfig(cwd);
584
+ if (!config)
585
+ return new Map();
586
+ let registry;
587
+ try {
588
+ registry = parseRegistrySource(config.source);
589
+ }
590
+ catch (error) {
591
+ console.log(chalk.yellow(`Warning: invalid registry.spec.source in .atw/config.yaml: ${error instanceof Error ? error.message : String(error)}`));
592
+ return new Map();
593
+ }
594
+ const probe = await probeRegistryIndex(`${registry.rawBaseUrl}/index.json`, registry);
595
+ if (probe.templates.length > 0) {
596
+ if (!config.template) {
597
+ console.log(chalk.gray("Registry spec update skipped: marketplace registries require registry.spec.template."));
598
+ return new Map();
599
+ }
600
+ const template = probe.templates.find((candidate) => candidate.id === config.template);
601
+ if (!template) {
602
+ console.log(chalk.yellow(`Warning: registry spec update skipped: template "${config.template}" was not found in registry index.`));
603
+ return new Map();
604
+ }
605
+ const tempRoot = await fs.promises.mkdtemp(path.join(os.tmpdir(), "atw-registry-template-"));
606
+ try {
607
+ const result = await downloadTemplateById(tempRoot, config.template, "overwrite", template, registry, undefined, probe.backend);
608
+ if (!result.success) {
609
+ console.log(chalk.yellow(`Warning: registry spec update skipped: ${result.message}`));
610
+ return new Map();
611
+ }
612
+ return collectDirectoryFiles(path.join(tempRoot, PATHS.SPEC), PATHS.SPEC);
613
+ }
614
+ finally {
615
+ await removeDirectory(tempRoot);
616
+ }
617
+ }
618
+ if (!probe.isNotFound) {
619
+ console.log(chalk.yellow(`Warning: registry spec update skipped: ${probe.error?.message ?? "could not reach registry"}`));
620
+ return new Map();
621
+ }
622
+ const result = await fetchRegistrySpecTemplates(registry, probe.backend);
623
+ if (!result.success) {
624
+ console.log(chalk.yellow(`Warning: registry spec update skipped: ${result.message ?? "download failed"}`));
625
+ return new Map();
626
+ }
627
+ return result.files;
628
+ }
629
+ async function collectTemplateFiles(cwd, extraPlatforms,
630
+ /**
631
+ * Bypass `update.skip` when collecting templates. Enable this for breaking
632
+ * releases so newly added files (e.g. a new `continue.md`) and template
633
+ * updates can land even under skip-protected paths. Without this, users with
634
+ * `.claude/commands/` in their skip list would silently miss new commands.
635
+ * Existing user customizations are still guarded at WRITE time via the
636
+ * "Modified by you" conflict prompt — they can skip per-file there.
637
+ */
638
+ bypassUpdateSkip = false) {
639
+ const files = new Map();
640
+ const platforms = getConfiguredPlatforms(cwd);
641
+ if (extraPlatforms) {
642
+ for (const p of extraPlatforms) {
643
+ platforms.add(p);
644
+ }
645
+ }
646
+ // Python scripts (single source of truth: getAllScripts())
647
+ for (const [scriptPath, content] of getAllScripts()) {
648
+ files.set(`${PATHS.SCRIPTS}/${scriptPath}`, content);
649
+ }
650
+ // Channel runtime agent definitions (single source of truth: getAllAgents()).
651
+ // Backfilled by `atw update` if missing so users who installed before the
652
+ // bundled agents existed pick them up. Edited files take the standard
653
+ // modified-file prompt path.
654
+ for (const [agentFile, content] of getAllAgents()) {
655
+ files.set(`${PATHS.AGENTS}/${agentFile}`, content);
656
+ }
657
+ // Configuration
658
+ // Order matters: registry first (it becomes part of the effective template),
659
+ // then the general local-key carry, so `registry:` is not carried twice.
660
+ files.set(`${DIR_NAMES.WORKFLOW}/config.yaml`, preserveLocalConfig(cwd, preserveExistingRegistryConfig(cwd, configYamlTemplate)));
661
+ files.set(`${DIR_NAMES.WORKFLOW}/.gitignore`, gitignoreTemplate);
662
+ // workflow.md is included here because it is runtime-parsed by
663
+ // get_context.py and shared hooks. Keep it on the normal template update
664
+ // path: if the installed file still matches the tracked hash, update the
665
+ // whole file. If the user edited it, the standard modified-file prompt /
666
+ // --force behavior applies. Partial tag-block merging is unsafe because
667
+ // platform routing markers outside [workflow-state:*] blocks are also
668
+ // script-consumed.
669
+ files.set(`${DIR_NAMES.WORKFLOW}/workflow.md`, workflowMdTemplate);
670
+ // workspace/index.md stays excluded — it's runtime-appended by add_session.py
671
+ // (journal index) and has no script-parsed structure.
672
+ files.set(FILE_NAMES.AGENTS, buildAgentsMdTemplate(cwd));
673
+ // Platform-specific templates (only for configured platforms)
674
+ for (const platformId of platforms) {
675
+ const platformFiles = collectPlatformTemplates(platformId);
676
+ if (platformFiles) {
677
+ for (const [filePath, content] of platformFiles) {
678
+ files.set(filePath, content);
679
+ }
680
+ if (platformId === "copilot") {
681
+ files.set(COPILOT_INSTRUCTIONS_PATH, buildCopilotInstructionsTemplate(cwd));
682
+ }
683
+ }
684
+ }
685
+ // Users configure sub-agent models by editing `model` /
686
+ // `model_reasoning_effort` directly on the generated agent tomls. Preserve
687
+ // those two keys from the on-disk files into the freshly rendered desired
688
+ // content so a project whose only local edit is these keys is not flagged
689
+ // as a modified-file conflict by the hash comparison below.
690
+ if (platforms.has("codex")) {
691
+ preserveCodexAgentModelKeys(cwd, files);
692
+ }
693
+ preserveExistingClaudeStatusLine(cwd, files);
694
+ for (const [filePath, content] of await collectRegistrySpecTemplates(cwd)) {
695
+ files.set(filePath, content);
696
+ }
697
+ // Apply update.skip from config.yaml (unless bypassed for breaking release)
698
+ if (!bypassUpdateSkip) {
699
+ const skipPaths = loadUpdateSkipPaths(cwd);
700
+ if (skipPaths.length > 0) {
701
+ for (const [filePath] of [...files]) {
702
+ if (skipPaths.some((skip) => filePath === skip ||
703
+ filePath.startsWith(skip.endsWith("/") ? skip : skip + "/"))) {
704
+ files.delete(filePath);
705
+ }
706
+ }
707
+ }
708
+ }
709
+ // Apply python3→python replacement for Windows consistency with init-time writes
710
+ for (const [filePath, content] of files) {
711
+ files.set(filePath, replacePythonCommandLiterals(content));
712
+ }
713
+ return files;
714
+ }
715
+ /**
716
+ * Analyze changes between current files and templates
717
+ *
718
+ * Uses hash tracking to distinguish between:
719
+ * - User didn't modify + template same = skip (unchangedFiles)
720
+ * - User didn't modify + template updated = auto-update (autoUpdateFiles)
721
+ * - User modified = needs confirmation (changedFiles)
722
+ */
723
+ function analyzeChanges(cwd, hashes, templates) {
724
+ const result = {
725
+ newFiles: [],
726
+ unchangedFiles: [],
727
+ autoUpdateFiles: [],
728
+ changedFiles: [],
729
+ userDeletedFiles: [],
730
+ protectedPaths: PROTECTED_PATHS,
731
+ };
732
+ for (const [relativePath, newContent] of templates) {
733
+ const fullPath = path.join(cwd, relativePath);
734
+ const exists = fs.existsSync(fullPath);
735
+ const change = {
736
+ path: fullPath,
737
+ relativePath,
738
+ newContent,
739
+ status: "new",
740
+ };
741
+ if (!exists) {
742
+ const storedHash = hashes[relativePath];
743
+ if (storedHash) {
744
+ // Previously installed but user deleted — respect deletion
745
+ result.userDeletedFiles.push(change);
746
+ }
747
+ else {
748
+ change.status = "new";
749
+ result.newFiles.push(change);
750
+ }
751
+ }
752
+ else {
753
+ const existingContent = fs.readFileSync(fullPath, "utf-8");
754
+ if (existingContent === newContent) {
755
+ // Content same as template - already up to date
756
+ change.status = "unchanged";
757
+ result.unchangedFiles.push(change);
758
+ }
759
+ else {
760
+ // Content differs - check if user modified or template updated
761
+ const storedHash = hashes[relativePath];
762
+ const currentHash = computeHash(existingContent);
763
+ if ((storedHash && storedHash === currentHash) ||
764
+ (!storedHash &&
765
+ isKnownUntrackedTemplate(relativePath, existingContent)) ||
766
+ (!storedHash &&
767
+ isSafeUntrackedCopilotInstructionsMerge(relativePath, existingContent, newContent))) {
768
+ // Either the tracked hash matches, or this is a known pristine template
769
+ // from before the path was hash-tracked. Safe to auto-update.
770
+ change.status = "changed";
771
+ result.autoUpdateFiles.push(change);
772
+ }
773
+ else {
774
+ // Hash differs (or no stored hash) - user modified the file
775
+ // Needs confirmation
776
+ change.status = "changed";
777
+ result.changedFiles.push(change);
778
+ }
779
+ }
780
+ }
781
+ }
782
+ return result;
783
+ }
784
+ /**
785
+ * Receipt entries that are wrong or missing for a file that is already
786
+ * byte-identical to its template.
787
+ *
788
+ * Nothing else repairs these. `analyzeChanges` classifies such a file
789
+ * `unchanged`, and the write-back draws only from `newFiles`,
790
+ * `autoUpdateFiles` and overwritten `changedFiles` — so a poisoned or absent
791
+ * entry beside a pristine file survives every subsequent `atw update`,
792
+ * however many times it is run. Identical template content across versions is
793
+ * not what saves such an entry from going stale; it is precisely what freezes
794
+ * it, because the file never leaves the `unchanged` bucket.
795
+ *
796
+ * Recording the template's hash here cannot bless a local edit. Membership in
797
+ * `unchangedFiles` means the file on disk already *is* the template, byte for
798
+ * byte, so the value written is the one a correct receipt would already hold.
799
+ * A genuinely customized file differs from its template, lands in
800
+ * `changedFiles`, and is never seen by this function.
801
+ *
802
+ * That also leaves the mixed-ownership paths — `AGENTS.md`,
803
+ * `.github/copilot-instructions.md`, `.atw/config.yaml` — free to differ
804
+ * from their recorded hash, which for them is the correct state: once the
805
+ * repository has appended its own content they are no longer `unchanged`.
806
+ */
807
+ function collectUnchangedFileHashRepairs(changes, hashes) {
808
+ const files = new Map();
809
+ for (const file of changes.unchangedFiles) {
810
+ const key = toPosix(file.relativePath);
811
+ const recorded = hashes[key];
812
+ if (recorded === undefined) {
813
+ // A missing entry is only an omission for a path the receipt is meant
814
+ // to carry. `EXCLUDE_FROM_HASH` holds paths deliberately left out —
815
+ // `.atw/.gitignore` among them — and adding those here would put
816
+ // this path in disagreement with `initializeHashes` about what the
817
+ // receipt tracks at all.
818
+ if (!shouldExcludeFromHash(key)) {
819
+ files.set(key, file.newContent);
820
+ }
821
+ continue;
822
+ }
823
+ // An entry that already exists and disagrees with the file is repaired
824
+ // whatever the path: a wrong value is strictly worse than an absent one,
825
+ // because it reads as a real local modification.
826
+ if (recorded !== computeHash(file.newContent)) {
827
+ files.set(key, file.newContent);
828
+ }
829
+ }
830
+ return files;
831
+ }
832
+ /**
833
+ * Print change summary
834
+ */
835
+ function printChangeSummary(changes) {
836
+ console.log("\nScanning for changes...\n");
837
+ if (changes.newFiles.length > 0) {
838
+ console.log(chalk.green(" New files (will add):"));
839
+ for (const file of changes.newFiles) {
840
+ console.log(chalk.green(` + ${file.relativePath}`));
841
+ }
842
+ console.log("");
843
+ }
844
+ if (changes.autoUpdateFiles.length > 0) {
845
+ console.log(chalk.cyan(" Template updated (will auto-update):"));
846
+ for (const file of changes.autoUpdateFiles) {
847
+ console.log(chalk.cyan(` ↑ ${file.relativePath}`));
848
+ }
849
+ console.log("");
850
+ }
851
+ if (changes.unchangedFiles.length > 0) {
852
+ console.log(chalk.gray(" Unchanged files (will skip):"));
853
+ for (const file of changes.unchangedFiles.slice(0, 5)) {
854
+ console.log(chalk.gray(` ā—‹ ${file.relativePath}`));
855
+ }
856
+ if (changes.unchangedFiles.length > 5) {
857
+ console.log(chalk.gray(` ... and ${changes.unchangedFiles.length - 5} more`));
858
+ }
859
+ console.log("");
860
+ }
861
+ if (changes.changedFiles.length > 0) {
862
+ console.log(chalk.yellow(" Modified by you (need your decision):"));
863
+ for (const file of changes.changedFiles) {
864
+ console.log(chalk.yellow(` ? ${file.relativePath}`));
865
+ }
866
+ console.log("");
867
+ }
868
+ if (changes.userDeletedFiles.length > 0) {
869
+ console.log(chalk.gray(" Deleted by you (preserved):"));
870
+ for (const file of changes.userDeletedFiles) {
871
+ console.log(chalk.gray(` \u2715 ${file.relativePath}`));
872
+ }
873
+ console.log("");
874
+ }
875
+ // Only show protected paths that actually exist
876
+ const existingProtectedPaths = changes.protectedPaths.filter((p) => {
877
+ const fullPath = path.join(process.cwd(), p);
878
+ return fs.existsSync(fullPath);
879
+ });
880
+ if (existingProtectedPaths.length > 0) {
881
+ console.log(chalk.gray(" User data (preserved):"));
882
+ for (const protectedPath of existingProtectedPaths) {
883
+ console.log(chalk.gray(` ā—‹ ${protectedPath}/`));
884
+ }
885
+ console.log("");
886
+ }
887
+ }
888
+ /**
889
+ * Prompt user for conflict resolution
890
+ */
891
+ async function promptConflictResolution(file, options, applyToAll) {
892
+ // If we have a batch action, use it
893
+ if (applyToAll.action) {
894
+ return applyToAll.action;
895
+ }
896
+ // Check command-line options
897
+ if (options.force) {
898
+ return "overwrite";
899
+ }
900
+ if (options.skipAll) {
901
+ return "skip";
902
+ }
903
+ if (options.createNew) {
904
+ return "create-new";
905
+ }
906
+ // Interactive prompt
907
+ const { action } = await inquirer.prompt([
908
+ {
909
+ type: "list",
910
+ name: "action",
911
+ message: `${file.relativePath} has changes.`,
912
+ choices: [
913
+ {
914
+ name: "[1] Overwrite - Replace with new version",
915
+ value: "overwrite",
916
+ },
917
+ { name: "[2] Skip - Keep your current version", value: "skip" },
918
+ {
919
+ name: "[3] Create copy - Save new version as .new",
920
+ value: "create-new",
921
+ },
922
+ { name: "[a] Apply Overwrite to all", value: "overwrite-all" },
923
+ { name: "[s] Apply Skip to all", value: "skip-all" },
924
+ { name: "[n] Apply Create copy to all", value: "create-new-all" },
925
+ ],
926
+ default: "skip",
927
+ },
928
+ ]);
929
+ if (action === "overwrite-all") {
930
+ applyToAll.action = "overwrite";
931
+ return "overwrite";
932
+ }
933
+ if (action === "skip-all") {
934
+ applyToAll.action = "skip";
935
+ return "skip";
936
+ }
937
+ if (action === "create-new-all") {
938
+ applyToAll.action = "create-new";
939
+ return "create-new";
940
+ }
941
+ return action;
942
+ }
943
+ /**
944
+ * Create a timestamped backup directory path
945
+ */
946
+ function createBackupDirPath(cwd) {
947
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
948
+ return path.join(cwd, DIR_NAMES.WORKFLOW, `.backup-${timestamp}`);
949
+ }
950
+ /**
951
+ * Backup a single file to the backup directory
952
+ */
953
+ function backupFile(cwd, backupDir, relativePath) {
954
+ const srcPath = path.join(cwd, relativePath);
955
+ if (!fs.existsSync(srcPath))
956
+ return;
957
+ const backupPath = path.join(backupDir, relativePath);
958
+ fs.mkdirSync(path.dirname(backupPath), { recursive: true });
959
+ fs.copyFileSync(srcPath, backupPath);
960
+ }
961
+ /**
962
+ * Directories to backup as complete snapshot (derived from platform registry)
963
+ */
964
+ const BACKUP_DIRS = ALL_MANAGED_DIRS;
965
+ /** Root-level managed files to include in update backups. */
966
+ const BACKUP_FILES = [FILE_NAMES.AGENTS];
967
+ /**
968
+ * Patterns to exclude from backup (user data that shouldn't be backed up)
969
+ */
970
+ const BACKUP_EXCLUDE_PATTERNS = [
971
+ ".backup-", // Previous backups
972
+ "/node_modules", // Installed dependencies; restore via package manager
973
+ "/workspace/", // Developer workspace (user data)
974
+ "/tasks/", // Task data (user data)
975
+ "/spec/", // Spec files (user-customized content)
976
+ "/backlog/", // Backlog data (user data)
977
+ // Platform-native worktree dirs — these are full sub-repos the CLI
978
+ // spawns for parallel sessions. Backing them up on every update would
979
+ // snapshot the entire nested working tree. Confirmed conventions:
980
+ // Claude Code: .claude/worktrees/
981
+ // Cursor CLI: .cursor/worktrees/
982
+ // Gemini CLI: .gemini/worktrees/
983
+ // Matches any platform using the same convention (future-proof).
984
+ "/worktrees/",
985
+ "/worktree/",
986
+ ];
987
+ /**
988
+ * Check if a path should be excluded from backup
989
+ * @internal Exported for testing only
990
+ */
991
+ export function shouldExcludeFromBackup(relativePath) {
992
+ // Normalize Windows backslashes to forward slashes so patterns like
993
+ // "/worktrees/" / "/tasks/" match regardless of host OS. Without this,
994
+ // Windows `path.relative` returns `.claude\worktrees\...` and none of
995
+ // the slash-prefixed exclude patterns trigger — which causes
996
+ // `collectAllFiles` to descend into platform worktrees (full nested
997
+ // project copies) and explode the scan. Same normalization pattern
998
+ // used by `isManagedPath` in configurators/index.ts.
999
+ const normalized = relativePath.replace(/\\/g, "/");
1000
+ for (const pattern of BACKUP_EXCLUDE_PATTERNS) {
1001
+ if (normalized.includes(pattern)) {
1002
+ return true;
1003
+ }
1004
+ }
1005
+ return false;
1006
+ }
1007
+ /**
1008
+ * Create complete snapshot backup of all managed directories
1009
+ * Backs up all managed platform/workflow directories entirely
1010
+ * (excluding user data like workspace/, tasks/, backlog/)
1011
+ */
1012
+ function createFullBackup(cwd) {
1013
+ const backupDir = createBackupDirPath(cwd);
1014
+ let hasFiles = false;
1015
+ for (const dir of BACKUP_DIRS) {
1016
+ const dirPath = path.join(cwd, dir);
1017
+ if (!fs.existsSync(dirPath))
1018
+ continue;
1019
+ const files = collectAllFiles(dirPath, cwd);
1020
+ for (const fullPath of files) {
1021
+ const relativePath = path.relative(cwd, fullPath);
1022
+ // Skip excluded paths
1023
+ if (shouldExcludeFromBackup(relativePath))
1024
+ continue;
1025
+ // Create backup
1026
+ if (!hasFiles) {
1027
+ fs.mkdirSync(backupDir, { recursive: true });
1028
+ hasFiles = true;
1029
+ }
1030
+ backupFile(cwd, backupDir, relativePath);
1031
+ }
1032
+ }
1033
+ for (const relativePath of BACKUP_FILES) {
1034
+ const fullPath = path.join(cwd, relativePath);
1035
+ if (!fs.existsSync(fullPath))
1036
+ continue;
1037
+ if (shouldExcludeFromBackup(relativePath))
1038
+ continue;
1039
+ if (!hasFiles) {
1040
+ fs.mkdirSync(backupDir, { recursive: true });
1041
+ hasFiles = true;
1042
+ }
1043
+ backupFile(cwd, backupDir, relativePath);
1044
+ }
1045
+ return hasFiles ? backupDir : null;
1046
+ }
1047
+ /**
1048
+ * Update version file
1049
+ */
1050
+ function updateVersionFile(cwd) {
1051
+ const versionPath = path.join(cwd, DIR_NAMES.WORKFLOW, ".version");
1052
+ fs.writeFileSync(versionPath, VERSION);
1053
+ }
1054
+ /**
1055
+ * Get current installed version
1056
+ */
1057
+ function getInstalledVersion(cwd) {
1058
+ const versionPath = path.join(cwd, DIR_NAMES.WORKFLOW, ".version");
1059
+ if (fs.existsSync(versionPath)) {
1060
+ return fs.readFileSync(versionPath, "utf-8").trim();
1061
+ }
1062
+ return "unknown";
1063
+ }
1064
+ /**
1065
+ * Fetch latest version from npm registry
1066
+ */
1067
+ async function getLatestNpmVersion() {
1068
+ try {
1069
+ const response = await fetch(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`);
1070
+ if (!response.ok) {
1071
+ return null;
1072
+ }
1073
+ const data = (await response.json());
1074
+ return data.version ?? null;
1075
+ }
1076
+ catch {
1077
+ return null;
1078
+ }
1079
+ }
1080
+ /**
1081
+ * Recursively collect all files in a directory
1082
+ */
1083
+ function collectAllFiles(dirPath, cwd = process.cwd()) {
1084
+ if (!fs.existsSync(dirPath))
1085
+ return [];
1086
+ const rootStat = fs.statSync(dirPath);
1087
+ if (rootStat.isFile()) {
1088
+ return [dirPath];
1089
+ }
1090
+ if (!rootStat.isDirectory()) {
1091
+ return [];
1092
+ }
1093
+ const files = [];
1094
+ const stack = [dirPath];
1095
+ while (stack.length > 0) {
1096
+ const currentDir = stack.pop();
1097
+ if (!currentDir)
1098
+ continue;
1099
+ const entries = fs.readdirSync(currentDir, { withFileTypes: true });
1100
+ for (const entry of entries) {
1101
+ const fullPath = path.join(currentDir, entry.name);
1102
+ const relativePath = path.relative(cwd, fullPath);
1103
+ // Never follow symlinks / Windows directory junctions — a junction
1104
+ // pointing at an ancestor would loop the scan forever. Node's
1105
+ // `isSymbolicLink()` returns true for NTFS junctions since v12.
1106
+ if (entry.isSymbolicLink())
1107
+ continue;
1108
+ if (entry.isDirectory()) {
1109
+ if (!shouldExcludeFromBackup(relativePath)) {
1110
+ stack.push(fullPath);
1111
+ }
1112
+ }
1113
+ else if (entry.isFile()) {
1114
+ files.push(fullPath);
1115
+ }
1116
+ }
1117
+ }
1118
+ return files;
1119
+ }
1120
+ /**
1121
+ * Whether every file under `dirRelativePath` byte-matches the CURRENT
1122
+ * template content for its path. Stricter than {@link isDirectorySafeToReplace},
1123
+ * which also accepts files that are merely unmodified relative to an old
1124
+ * stored hash (i.e. stale-but-untouched). Used to decide the safe *direction*
1125
+ * of a rename-dir merge when both source and target exist: if the target
1126
+ * already holds canonical current-version bytes, the source (however it got
1127
+ * there) must not be allowed to overwrite it with older/differently-flavored
1128
+ * content (— a legacy `.pi/skills/` copy rendered with the Pi-specific
1129
+ * resolver must not clobber the shared, neutral `.agents/skills/` content
1130
+ * Codex/Gemini already wrote).
1131
+ */
1132
+ function dirMatchesCurrentTemplates(cwd, dirRelativePath, templates) {
1133
+ const dirFullPath = path.join(cwd, dirRelativePath);
1134
+ if (!fs.existsSync(dirFullPath))
1135
+ return false;
1136
+ const files = collectAllFiles(dirFullPath, cwd);
1137
+ if (files.length === 0)
1138
+ return false;
1139
+ for (const fullPath of files) {
1140
+ const relativePath = toPosix(path.relative(cwd, fullPath));
1141
+ const templateContent = templates.get(relativePath);
1142
+ if (templateContent === undefined)
1143
+ return false;
1144
+ if (fs.readFileSync(fullPath, "utf-8") !== templateContent)
1145
+ return false;
1146
+ }
1147
+ return true;
1148
+ }
1149
+ /**
1150
+ * Check if a directory only contains unmodified template files
1151
+ * Returns true if safe to delete:
1152
+ * - All files are tracked and unmodified, OR
1153
+ * - All files match current template content (even if not tracked)
1154
+ */
1155
+ function isDirectorySafeToReplace(cwd, dirRelativePath, hashes, templates) {
1156
+ const dirFullPath = path.join(cwd, dirRelativePath);
1157
+ if (!fs.existsSync(dirFullPath))
1158
+ return true;
1159
+ const files = collectAllFiles(dirFullPath, cwd);
1160
+ if (files.length === 0)
1161
+ return true; // Empty directory is safe
1162
+ for (const fullPath of files) {
1163
+ // POSIX-normalize: hashes/templates keys are persisted as POSIX, but
1164
+ // `path.relative` returns OS-native separators (backslash on Windows).
1165
+ const relativePath = toPosix(path.relative(cwd, fullPath));
1166
+ const storedHash = hashes[relativePath];
1167
+ const templateContent = templates.get(relativePath);
1168
+ // Check if file matches template content (handles untracked files)
1169
+ if (templateContent) {
1170
+ const currentContent = fs.readFileSync(fullPath, "utf-8");
1171
+ if (currentContent === templateContent) {
1172
+ // File matches template - safe
1173
+ continue;
1174
+ }
1175
+ }
1176
+ // Check if file is tracked and unmodified
1177
+ if (storedHash && !isTemplateModified(cwd, relativePath, hashes)) {
1178
+ // Tracked and unmodified - safe
1179
+ continue;
1180
+ }
1181
+ // File is either user-created or user-modified - not safe
1182
+ return false;
1183
+ }
1184
+ return true;
1185
+ }
1186
+ /**
1187
+ * Recursively delete a directory
1188
+ */
1189
+ function removeDirectoryRecursive(dirPath) {
1190
+ if (!fs.existsSync(dirPath))
1191
+ return;
1192
+ fs.rmSync(dirPath, { recursive: true, force: true });
1193
+ }
1194
+ /**
1195
+ * Check if a file is safe to overwrite (matches template content)
1196
+ */
1197
+ function isFileSafeToReplace(cwd, relativePath, templates) {
1198
+ const fullPath = path.join(cwd, relativePath);
1199
+ if (!fs.existsSync(fullPath))
1200
+ return true;
1201
+ const templateContent = templates.get(relativePath);
1202
+ if (!templateContent)
1203
+ return false; // Not a template file
1204
+ const currentContent = fs.readFileSync(fullPath, "utf-8");
1205
+ return currentContent === templateContent;
1206
+ }
1207
+ /**
1208
+ * Classify migrations based on file state and user modifications
1209
+ */
1210
+ /**
1211
+ * Whether the manifest records any file under `dirRelativePath` — i.e. whether
1212
+ * ATW actually created this directory. Used to gate rename-dir migrations:
1213
+ * a directory ATW never wrote (e.g. a user's own `.windsurf/` editor
1214
+ * config that merely shares a path with a retired ATW platform dir) must
1215
+ * not be auto-moved.
1216
+ */
1217
+ export function dirHasManifestEntries(dirRelativePath, hashes) {
1218
+ const prefix = dirRelativePath.endsWith("/")
1219
+ ? dirRelativePath
1220
+ : dirRelativePath + "/";
1221
+ return Object.keys(hashes).some((key) => key === dirRelativePath || key.startsWith(prefix));
1222
+ }
1223
+ export function classifyMigrations(migrations, cwd, hashes, templates) {
1224
+ const result = {
1225
+ auto: [],
1226
+ confirm: [],
1227
+ conflict: [],
1228
+ skip: [],
1229
+ };
1230
+ for (const item of migrations) {
1231
+ // safe-file-delete handled separately (not via --migrate)
1232
+ if (item.type === "safe-file-delete")
1233
+ continue;
1234
+ // Enforce PROTECTED_PATHS — never migrate FROM protected paths (prevents moving/deleting user data)
1235
+ if (isProtectedPath(item.from)) {
1236
+ result.skip.push(item);
1237
+ continue;
1238
+ }
1239
+ // For non-rename types, also block writing TO protected paths
1240
+ // rename/rename-dir are allowed to target protected paths (e.g. renames into .atw/workspace)
1241
+ if (item.to &&
1242
+ isProtectedPath(item.to) &&
1243
+ item.type !== "rename" &&
1244
+ item.type !== "rename-dir") {
1245
+ result.skip.push(item);
1246
+ continue;
1247
+ }
1248
+ const oldPath = path.join(cwd, item.from);
1249
+ const oldExists = fs.existsSync(oldPath);
1250
+ if (!oldExists) {
1251
+ // Old file doesn't exist, nothing to migrate
1252
+ result.skip.push(item);
1253
+ continue;
1254
+ }
1255
+ if (item.type === "rename" && item.to) {
1256
+ const newPath = path.join(cwd, item.to);
1257
+ const newExists = fs.existsSync(newPath);
1258
+ if (newExists) {
1259
+ // Both exist - check if new file matches template (safe to overwrite)
1260
+ if (isFileSafeToReplace(cwd, item.to, templates)) {
1261
+ // New file is just template content - safe to delete and rename
1262
+ result.auto.push(item);
1263
+ }
1264
+ else {
1265
+ // New file has user content - conflict
1266
+ result.conflict.push(item);
1267
+ }
1268
+ }
1269
+ else if (isTemplateModified(cwd, item.from, hashes)) {
1270
+ // User has modified the file - needs confirmation
1271
+ result.confirm.push(item);
1272
+ }
1273
+ else {
1274
+ // Unmodified template - safe to auto-migrate
1275
+ result.auto.push(item);
1276
+ }
1277
+ }
1278
+ else if (item.type === "rename-dir" && item.to) {
1279
+ const newPath = path.join(cwd, item.to);
1280
+ const newExists = fs.existsSync(newPath);
1281
+ if (newExists) {
1282
+ // Target exists - check if it only contains unmodified template files
1283
+ if (isDirectorySafeToReplace(cwd, item.to, hashes, templates)) {
1284
+ // Safe to delete target and rename source
1285
+ result.auto.push(item);
1286
+ }
1287
+ else {
1288
+ // Target has user modifications - conflict
1289
+ result.conflict.push(item);
1290
+ }
1291
+ }
1292
+ else if (dirHasManifestEntries(item.from, hashes)) {
1293
+ // ATW created this directory (the manifest tracks files under it),
1294
+ // so the rename is ours to make.
1295
+ result.auto.push(item);
1296
+ }
1297
+ else {
1298
+ // Target absent and the source has no manifest record: this is very
1299
+ // likely a user-owned directory that merely shares a path with a
1300
+ // retired ATW platform dir (e.g. a real `.windsurf/` editor
1301
+ // config). Skipping avoids silently moving the user's data out from
1302
+ // under their editor — even under --force, since skip never executes.
1303
+ result.skip.push(item);
1304
+ }
1305
+ }
1306
+ else if (item.type === "delete") {
1307
+ if (isTemplateModified(cwd, item.from, hashes)) {
1308
+ // User has modified - needs confirmation before delete
1309
+ result.confirm.push(item);
1310
+ }
1311
+ else {
1312
+ // Unmodified - safe to auto-delete
1313
+ result.auto.push(item);
1314
+ }
1315
+ }
1316
+ }
1317
+ return result;
1318
+ }
1319
+ /**
1320
+ * Print migration summary
1321
+ */
1322
+ function printMigrationSummary(classified) {
1323
+ const total = classified.auto.length +
1324
+ classified.confirm.length +
1325
+ classified.conflict.length +
1326
+ classified.skip.length;
1327
+ if (total === 0) {
1328
+ console.log(chalk.gray(" No migrations to apply.\n"));
1329
+ return;
1330
+ }
1331
+ if (classified.auto.length > 0) {
1332
+ console.log(chalk.green(" āœ“ Auto-migrate (unmodified):"));
1333
+ for (const item of classified.auto) {
1334
+ if (item.type === "rename") {
1335
+ console.log(chalk.green(` ${item.from} → ${item.to}`));
1336
+ }
1337
+ else if (item.type === "rename-dir") {
1338
+ console.log(chalk.green(` [dir] ${item.from}/ → ${item.to}/`));
1339
+ }
1340
+ else {
1341
+ console.log(chalk.green(` āœ• ${item.from}`));
1342
+ }
1343
+ }
1344
+ console.log("");
1345
+ }
1346
+ if (classified.confirm.length > 0) {
1347
+ console.log(chalk.yellow(" ⚠ Requires confirmation (modified by user):"));
1348
+ for (const item of classified.confirm) {
1349
+ if (item.type === "rename") {
1350
+ console.log(chalk.yellow(` ${item.from} → ${item.to}`));
1351
+ }
1352
+ else {
1353
+ console.log(chalk.yellow(` āœ• ${item.from}`));
1354
+ }
1355
+ }
1356
+ console.log("");
1357
+ }
1358
+ if (classified.conflict.length > 0) {
1359
+ console.log(chalk.red(" ⊘ Conflict (both old and new exist):"));
1360
+ for (const item of classified.conflict) {
1361
+ if (item.type === "rename-dir") {
1362
+ console.log(chalk.red(` [dir] ${item.from}/ ↔ ${item.to}/`));
1363
+ }
1364
+ else {
1365
+ console.log(chalk.red(` ${item.from} ↔ ${item.to}`));
1366
+ }
1367
+ }
1368
+ console.log(chalk.gray(" → Resolve manually: merge or delete one, then re-run update"));
1369
+ console.log("");
1370
+ }
1371
+ if (classified.skip.length > 0) {
1372
+ console.log(chalk.gray(" ā—‹ Skipping (not found, protected, or not ATW-owned):"));
1373
+ for (const item of classified.skip.slice(0, 3)) {
1374
+ console.log(chalk.gray(` ${item.from}`));
1375
+ }
1376
+ if (classified.skip.length > 3) {
1377
+ console.log(chalk.gray(` ... and ${classified.skip.length - 3} more`));
1378
+ }
1379
+ console.log("");
1380
+ }
1381
+ }
1382
+ /**
1383
+ * Prompt user for migration action on a single item.
1384
+ *
1385
+ * Design notes:
1386
+ * - Default is `backup-rename`: safest — preserves user's content as a .backup
1387
+ * alongside the rename, so Enter-to-continue never destroys work or leaves
1388
+ * stale paths behind.
1389
+ * - "Skip" leaves a stale old path that won't be cleaned by later updates —
1390
+ * warn explicitly so users understand the consequence.
1391
+ * - Show manifest description + why-flagged so users can make an informed
1392
+ * choice without needing to dig through the diff.
1393
+ */
1394
+ async function promptMigrationAction(item) {
1395
+ const headline = item.type === "rename"
1396
+ ? `${chalk.cyan(item.from)} → ${chalk.green(item.to)}`
1397
+ : `${chalk.red("Delete")} ${chalk.cyan(item.from)}`;
1398
+ const description = item.description ?? "No description provided in manifest.";
1399
+ // Actions with inline guidance so users see the trade-off per choice.
1400
+ const renameLabel = item.type === "rename"
1401
+ ? "[r] Rename anyway — use if the file is unchanged, or any edits are fine to move as-is"
1402
+ : "[d] Delete anyway — use if you don't need this file (already migrated to replacement)";
1403
+ const backupLabel = item.type === "rename"
1404
+ ? "[b] Backup original, then proceed — SAFEST: writes <new-path>.backup with your current content, then renames"
1405
+ : "[b] Backup original, then proceed — SAFEST: writes <path>.backup with your current content, then deletes";
1406
+ const skipLabel = item.type === "rename"
1407
+ ? "[s] Skip — leaves the old path in place (you'll see it flagged on future updates until cleaned up manually)"
1408
+ : "[s] Skip — keeps the deprecated file (you'll see it flagged on future updates until cleaned up manually)";
1409
+ // Prefer the per-migration `reason` (version-specific context authored in the
1410
+ // manifest) over a generic fallback. Hardcoding version-specific hints here
1411
+ // rots fast — every release gets a new set of edge cases.
1412
+ const whyFlagged = item.reason
1413
+ ? chalk.gray(item.reason
1414
+ .split("\n")
1415
+ .map((line) => ` ${line}`)
1416
+ .join("\n"))
1417
+ : chalk.gray(` Why prompted: file content doesn't match the ATW template hash\n` +
1418
+ ` for this path — usually local customization. If unsure, pick [b].`);
1419
+ const message = [
1420
+ headline,
1421
+ "",
1422
+ chalk.bold(" What:") + " " + description,
1423
+ whyFlagged,
1424
+ "",
1425
+ chalk.bold(" Choose:"),
1426
+ ].join("\n");
1427
+ const { choice } = await inquirer.prompt([
1428
+ {
1429
+ type: "list",
1430
+ name: "choice",
1431
+ message,
1432
+ choices: [
1433
+ { name: backupLabel, value: "backup-rename" },
1434
+ { name: renameLabel, value: "rename" },
1435
+ { name: skipLabel, value: "skip" },
1436
+ ],
1437
+ default: "backup-rename",
1438
+ },
1439
+ ]);
1440
+ return choice;
1441
+ }
1442
+ /**
1443
+ * Sort migrations for safe execution order
1444
+ * - rename-dir with deeper paths first (to handle nested directories)
1445
+ * - rename-dir before rename/delete
1446
+ */
1447
+ /** @internal Exported for testing only */
1448
+ export function sortMigrationsForExecution(migrations) {
1449
+ return [...migrations].sort((a, b) => {
1450
+ // rename-dir should be sorted by path depth (deeper first)
1451
+ if (a.type === "rename-dir" && b.type === "rename-dir") {
1452
+ const aDepth = a.from.split("/").length;
1453
+ const bDepth = b.from.split("/").length;
1454
+ return bDepth - aDepth; // Deeper paths first
1455
+ }
1456
+ // rename-dir before rename/delete (directories first)
1457
+ if (a.type === "rename-dir" && b.type !== "rename-dir")
1458
+ return -1;
1459
+ if (a.type !== "rename-dir" && b.type === "rename-dir")
1460
+ return 1;
1461
+ return 0;
1462
+ });
1463
+ }
1464
+ /**
1465
+ * Execute classified migrations
1466
+ *
1467
+ * @param options.force - Force migrate modified files without asking
1468
+ * @param options.skipAll - Skip all modified files without asking
1469
+ * If neither is set, prompts interactively for modified files
1470
+ */
1471
+ export async function executeMigrations(classified, cwd, options, templates) {
1472
+ const result = {
1473
+ renamed: 0,
1474
+ deleted: 0,
1475
+ skipped: 0,
1476
+ conflicts: classified.conflict.length,
1477
+ };
1478
+ // Sort migrations for safe execution order
1479
+ const sortedAuto = sortMigrationsForExecution(classified.auto);
1480
+ // 1. Execute auto migrations (unmodified files and directories)
1481
+ for (const item of sortedAuto) {
1482
+ if (item.type === "rename" && item.to) {
1483
+ const oldPath = path.join(cwd, item.from);
1484
+ const newPath = path.join(cwd, item.to);
1485
+ // Ensure target directory exists
1486
+ fs.mkdirSync(path.dirname(newPath), { recursive: true });
1487
+ fs.renameSync(oldPath, newPath);
1488
+ // Update hash tracking
1489
+ renameHash(cwd, item.from, item.to);
1490
+ // Make executable if it's a script
1491
+ if (item.to.endsWith(".sh") || item.to.endsWith(".py")) {
1492
+ fs.chmodSync(newPath, "755");
1493
+ }
1494
+ // Clean up empty source directory
1495
+ cleanupEmptyDirs(cwd, path.dirname(item.from));
1496
+ result.renamed++;
1497
+ }
1498
+ else if (item.type === "rename-dir" && item.to) {
1499
+ const oldPath = path.join(cwd, item.from);
1500
+ const newPath = path.join(cwd, item.to);
1501
+ const oldPrefix = item.from.endsWith("/") ? item.from : item.from + "/";
1502
+ const newPrefix = item.to.endsWith("/") ? item.to : item.to + "/";
1503
+ // Target already exists and already holds canonical, current-version
1504
+ // content (e.g. Codex/Gemini already wrote the shared `.agents/skills/`
1505
+ // root before Pi's legacy `.pi/skills/` copy gets retired). Renaming
1506
+ // the source in would clobber good content with older/differently-
1507
+ // flavored bytes, so just drop the now-redundant source instead.
1508
+ if (fs.existsSync(newPath) &&
1509
+ dirMatchesCurrentTemplates(cwd, item.to, templates)) {
1510
+ removeDirectoryRecursive(oldPath);
1511
+ const hashes = loadHashes(cwd);
1512
+ const updatedHashes = {};
1513
+ for (const [hashPath, hashValue] of Object.entries(hashes)) {
1514
+ if (hashPath.startsWith(oldPrefix))
1515
+ continue; // source retired
1516
+ updatedHashes[hashPath] = hashValue;
1517
+ }
1518
+ saveHashes(cwd, updatedHashes);
1519
+ result.deleted++;
1520
+ continue;
1521
+ }
1522
+ // If target exists (safe to replace, already checked in classification)
1523
+ // delete it first before renaming
1524
+ if (fs.existsSync(newPath)) {
1525
+ removeDirectoryRecursive(newPath);
1526
+ }
1527
+ // Ensure parent directory exists
1528
+ fs.mkdirSync(path.dirname(newPath), { recursive: true });
1529
+ // Rename the entire directory (includes all user files)
1530
+ fs.renameSync(oldPath, newPath);
1531
+ // Batch update hash tracking for all files in the directory
1532
+ const hashes = loadHashes(cwd);
1533
+ const updatedHashes = {};
1534
+ for (const [hashPath, hashValue] of Object.entries(hashes)) {
1535
+ if (hashPath.startsWith(oldPrefix)) {
1536
+ // Rename path: old prefix -> new prefix
1537
+ const newHashPath = newPrefix + hashPath.slice(oldPrefix.length);
1538
+ updatedHashes[newHashPath] = hashValue;
1539
+ }
1540
+ else if (hashPath.startsWith(newPrefix)) {
1541
+ // Skip old hashes from deleted target directory
1542
+ // (they will be replaced by renamed source files)
1543
+ continue;
1544
+ }
1545
+ else {
1546
+ // Keep unchanged
1547
+ updatedHashes[hashPath] = hashValue;
1548
+ }
1549
+ }
1550
+ saveHashes(cwd, updatedHashes);
1551
+ result.renamed++;
1552
+ }
1553
+ else if (item.type === "delete") {
1554
+ const filePath = path.join(cwd, item.from);
1555
+ fs.unlinkSync(filePath);
1556
+ // Remove from hash tracking
1557
+ removeHash(cwd, item.from);
1558
+ // Clean up empty directory
1559
+ cleanupEmptyDirs(cwd, path.dirname(item.from));
1560
+ result.deleted++;
1561
+ }
1562
+ }
1563
+ // 2. Handle confirm items (modified files)
1564
+ // Note: All files are already backed up by createMigrationBackup before execution
1565
+ for (const item of classified.confirm) {
1566
+ let action;
1567
+ if (options.force) {
1568
+ // Force mode: proceed (already backed up)
1569
+ action = "rename";
1570
+ }
1571
+ else if (options.skipAll) {
1572
+ // Skip mode: skip all modified files
1573
+ action = "skip";
1574
+ }
1575
+ else {
1576
+ // Default: interactive prompt
1577
+ action = await promptMigrationAction(item);
1578
+ }
1579
+ if (action === "skip") {
1580
+ result.skipped++;
1581
+ continue;
1582
+ }
1583
+ // For `backup-rename`, leave an inline .backup copy of the user's modified
1584
+ // original next to the new location (for rename) or in place (for delete).
1585
+ // This is in addition to the full project snapshot at .atw/.backup-*/;
1586
+ // the inline copy is more discoverable when the user wants to diff or merge
1587
+ // their customizations against the new template.
1588
+ if (item.type === "rename" && item.to) {
1589
+ const oldPath = path.join(cwd, item.from);
1590
+ const newPath = path.join(cwd, item.to);
1591
+ fs.mkdirSync(path.dirname(newPath), { recursive: true });
1592
+ if (action === "backup-rename") {
1593
+ // Copy original alongside the new path before the rename overwrites nothing
1594
+ // (target dir is guaranteed fresh since `conflict` is handled elsewhere).
1595
+ fs.copyFileSync(oldPath, newPath + ".backup");
1596
+ }
1597
+ fs.renameSync(oldPath, newPath);
1598
+ renameHash(cwd, item.from, item.to);
1599
+ if (item.to.endsWith(".sh") || item.to.endsWith(".py")) {
1600
+ fs.chmodSync(newPath, "755");
1601
+ }
1602
+ // Clean up empty source directory
1603
+ cleanupEmptyDirs(cwd, path.dirname(item.from));
1604
+ result.renamed++;
1605
+ }
1606
+ else if (item.type === "delete") {
1607
+ const filePath = path.join(cwd, item.from);
1608
+ if (action === "backup-rename") {
1609
+ // Keep a .backup copy in place before deletion so the user can recover
1610
+ // inline without digging through .atw/.backup-*/.
1611
+ fs.copyFileSync(filePath, filePath + ".backup");
1612
+ }
1613
+ fs.unlinkSync(filePath);
1614
+ removeHash(cwd, item.from);
1615
+ // Clean up empty directory
1616
+ cleanupEmptyDirs(cwd, path.dirname(item.from));
1617
+ result.deleted++;
1618
+ }
1619
+ }
1620
+ // 3. Skip count already tracked (old files not found)
1621
+ result.skipped += classified.skip.length;
1622
+ return result;
1623
+ }
1624
+ /**
1625
+ * Print migration result summary
1626
+ */
1627
+ function printMigrationResult(result) {
1628
+ const parts = [];
1629
+ if (result.renamed > 0) {
1630
+ parts.push(`${result.renamed} renamed`);
1631
+ }
1632
+ if (result.deleted > 0) {
1633
+ parts.push(`${result.deleted} deleted`);
1634
+ }
1635
+ if (result.skipped > 0) {
1636
+ parts.push(`${result.skipped} skipped`);
1637
+ }
1638
+ if (result.conflicts > 0) {
1639
+ parts.push(`${result.conflicts} conflict${result.conflicts > 1 ? "s" : ""}`);
1640
+ }
1641
+ if (parts.length > 0) {
1642
+ console.log(chalk.cyan(`Migration complete: ${parts.join(", ")}`));
1643
+ }
1644
+ }
1645
+ /**
1646
+ * One-time migration: rename `traces-*.md` → `journal-*.md` in every
1647
+ * developer workspace directory.
1648
+ *
1649
+ * Never overwrites an existing `journal-N.md`: a newer session may already
1650
+ * have created it, and `.atw/workspace/` is excluded from the update
1651
+ * backup (see `BACKUP_EXCLUDE_PATTERNS`), so clobbering it would be
1652
+ * unrecoverable data loss. Conflicting `traces-N.md` files are left in place
1653
+ * and reported instead.
1654
+ */
1655
+ export function renameTracesToJournal(workspaceDir) {
1656
+ const skipped = [];
1657
+ let renamed = 0;
1658
+ if (!fs.existsSync(workspaceDir))
1659
+ return { renamed, skipped };
1660
+ for (const dev of fs.readdirSync(workspaceDir)) {
1661
+ const devPath = path.join(workspaceDir, dev);
1662
+ if (!fs.statSync(devPath).isDirectory())
1663
+ continue;
1664
+ for (const file of fs.readdirSync(devPath)) {
1665
+ if (!(file.startsWith("traces-") && file.endsWith(".md")))
1666
+ continue;
1667
+ const oldPath = path.join(devPath, file);
1668
+ const newPath = path.join(devPath, file.replace("traces-", "journal-"));
1669
+ if (fs.existsSync(newPath)) {
1670
+ skipped.push(oldPath);
1671
+ continue;
1672
+ }
1673
+ fs.renameSync(oldPath, newPath);
1674
+ renamed++;
1675
+ }
1676
+ }
1677
+ return { renamed, skipped };
1678
+ }
1679
+ /**
1680
+ * Main update command
1681
+ */
1682
+ export async function update(options) {
1683
+ const cwd = process.cwd();
1684
+ // Check if ATW is initialized
1685
+ if (!fs.existsSync(path.join(cwd, DIR_NAMES.WORKFLOW))) {
1686
+ console.log(chalk.red("Error: ATW not initialized in this directory."));
1687
+ console.log(chalk.gray("Run 'atw init' first."));
1688
+ return;
1689
+ }
1690
+ console.log(chalk.cyan("\nATW Update"));
1691
+ console.log(chalk.cyan("══════════════\n"));
1692
+ // Set up proxy before any network calls (npm version check)
1693
+ setupProxy();
1694
+ // Get versions
1695
+ const projectVersion = getInstalledVersion(cwd);
1696
+ const cliVersion = VERSION;
1697
+ const latestNpmVersion = await getLatestNpmVersion();
1698
+ // Version comparison
1699
+ const cliVsProject = compareVersions(cliVersion, projectVersion);
1700
+ const cliVsNpm = latestNpmVersion
1701
+ ? compareVersions(cliVersion, latestNpmVersion)
1702
+ : 0;
1703
+ // Display versions with context
1704
+ console.log(`Project version: ${chalk.white(projectVersion)}`);
1705
+ console.log(`CLI version: ${chalk.white(cliVersion)}`);
1706
+ if (latestNpmVersion) {
1707
+ console.log(`Latest on npm: ${chalk.white(latestNpmVersion)}`);
1708
+ }
1709
+ else {
1710
+ console.log(chalk.gray("Latest on npm: (unable to fetch)"));
1711
+ }
1712
+ console.log("");
1713
+ // Check if CLI is outdated compared to npm
1714
+ if (cliVsNpm < 0 && latestNpmVersion) {
1715
+ console.log(chalk.yellow(`āš ļø Your CLI (${cliVersion}) is behind npm (${latestNpmVersion}).`));
1716
+ console.log(chalk.yellow(` Run: atw upgrade\n`));
1717
+ }
1718
+ // Check for downgrade situation
1719
+ if (cliVsProject < 0) {
1720
+ console.log(chalk.red(`āŒ Cannot update: CLI version (${cliVersion}) < project version (${projectVersion})`));
1721
+ console.log(chalk.red(` This would DOWNGRADE your project!\n`));
1722
+ if (!options.allowDowngrade) {
1723
+ console.log(chalk.gray("Solutions:"));
1724
+ console.log(chalk.gray(` 1. Update your CLI: atw upgrade`));
1725
+ console.log(chalk.gray(` 2. Force downgrade: atw update --allow-downgrade\n`));
1726
+ return;
1727
+ }
1728
+ console.log(chalk.yellow("āš ļø --allow-downgrade flag set. Proceeding with downgrade...\n"));
1729
+ }
1730
+ // Migration metadata is displayed at the end to prevent scrolling off screen
1731
+ // Load template hashes for modification detection
1732
+ let hashes = loadHashes(cwd);
1733
+ const isFirstHashTracking = Object.keys(hashes).length === 0;
1734
+ // Handle unknown version - skip regular migrations but safe-file-delete still runs
1735
+ const isUnknownVersion = projectVersion === "unknown";
1736
+ if (isUnknownVersion) {
1737
+ console.log(chalk.yellow("āš ļø No version file found. Skipping migrations — run atw init to fix."));
1738
+ console.log(chalk.gray(" Template updates will still be applied."));
1739
+ console.log(chalk.gray(" Safe file cleanup will still run (hash-verified).\n"));
1740
+ }
1741
+ // Detect legacy Codex (has .agents/skills/ tracked by ATW but no .codex/)
1742
+ // NOTE: this MUST happen before pruneOrphanManifestKeys below, since the
1743
+ // detector reads the raw manifest looking for .agents/skills/ markers that
1744
+ // the prune step would otherwise consider orphans (codex hasn't been added
1745
+ // to configuredPlatforms yet at this point).
1746
+ const codexUpgradeNeeded = needsCodexUpgrade(cwd);
1747
+ if (codexUpgradeNeeded) {
1748
+ console.log(chalk.yellow(" Legacy Codex detected: .agents/skills/ tracked without .codex/ — will create .codex/ directory"));
1749
+ }
1750
+ // Self-heal poisoned manifests: prune entries that no current platform
1751
+ // configurator owns. This silently removes user-owned paths that early
1752
+ // buggy versions of `atw init` over-hashed (e.g. .codex/sessions/*).
1753
+ // Include codex in known-platforms when codexUpgradeNeeded so legacy Codex
1754
+ // markers under .agents/skills/ survive into the upgrade flow.
1755
+ {
1756
+ const configuredPlatforms = new Set(getConfiguredPlatforms(cwd));
1757
+ if (codexUpgradeNeeded)
1758
+ configuredPlatforms.add("codex");
1759
+ const prune = pruneOrphanManifestKeys(cwd, [...configuredPlatforms], hashes);
1760
+ if (prune.pruned.length > 0) {
1761
+ console.log(chalk.gray(` Pruned ${prune.pruned.length} orphan manifest entries from .template-hashes.json`));
1762
+ hashes = prune.hashes;
1763
+ }
1764
+ }
1765
+ // For breaking releases with recommendMigrate + --migrate, bypass update.skip
1766
+ // across the board (safe-file-delete, new file writes, template updates).
1767
+ // Why: honoring skip here leaves users forever half-migrated — old deprecated
1768
+ // files persist under skip-protected paths, new commands like `continue.md`
1769
+ // never land, and every future update re-flags the same mess. Rename
1770
+ // migrations already ignore update.skip; this makes the rest consistent
1771
+ // during a breaking upgrade. User customizations are still guarded by the
1772
+ // per-file conflict prompt ("Modified by you") at write time.
1773
+ const breakingBypass = options.migrate === true &&
1774
+ cliVsProject > 0 &&
1775
+ projectVersion !== "unknown" &&
1776
+ (() => {
1777
+ const md = getMigrationMetadata(projectVersion, cliVersion);
1778
+ return md.breaking && md.recommendMigrate;
1779
+ })();
1780
+ // Collect templates (used for both migration classification and change analysis)
1781
+ const templates = await collectTemplateFiles(cwd, codexUpgradeNeeded ? new Set(["codex"]) : undefined, breakingBypass);
1782
+ // Load update.skip paths (used for both safe-file-delete and template collection)
1783
+ const skipPaths = loadUpdateSkipPaths(cwd);
1784
+ // Collect safe-file-delete items from ALL manifests (hash match is the safety net)
1785
+ // This runs regardless of version — unknown version still gets safe cleanup
1786
+ const allMigrations = getAllMigrations();
1787
+ const safeFileDeletes = collectSafeFileDeletes(allMigrations, cwd, skipPaths, new Set(templates.keys()), breakingBypass);
1788
+ const hasSafeDeletes = safeFileDeletes.filter((c) => c.action === "delete").length > 0;
1789
+ // Check for pending regular migrations (skip if unknown version)
1790
+ let pendingMigrations = isUnknownVersion
1791
+ ? []
1792
+ : getMigrationsForVersion(projectVersion, cliVersion);
1793
+ // Also check for "orphaned" migrations - where source still exists but version says we shouldn't migrate
1794
+ // This handles cases where version was updated but migrations weren't applied
1795
+ const orphanedMigrations = allMigrations.filter((item) => {
1796
+ // Only check rename and rename-dir migrations
1797
+ if (item.type !== "rename" && item.type !== "rename-dir")
1798
+ return false;
1799
+ if (!item.from || !item.to)
1800
+ return false;
1801
+ const oldPath = path.join(cwd, item.from);
1802
+ const newPath = path.join(cwd, item.to);
1803
+ // Orphaned if: source exists AND target doesn't exist
1804
+ // AND this migration isn't already in pendingMigrations
1805
+ const sourceExists = fs.existsSync(oldPath);
1806
+ const targetExists = fs.existsSync(newPath);
1807
+ const alreadyPending = pendingMigrations.some((m) => m.from === item.from && m.to === item.to);
1808
+ return sourceExists && !targetExists && !alreadyPending;
1809
+ });
1810
+ // Add orphaned migrations to pending (they need to be applied)
1811
+ if (orphanedMigrations.length > 0) {
1812
+ console.log(chalk.yellow("āš ļø Detected incomplete migrations from previous updates:"));
1813
+ for (const item of orphanedMigrations) {
1814
+ console.log(chalk.yellow(` ${item.from} → ${item.to}`));
1815
+ }
1816
+ console.log("");
1817
+ pendingMigrations = [...pendingMigrations, ...orphanedMigrations];
1818
+ }
1819
+ const hasMigrations = pendingMigrations.length > 0;
1820
+ // Classify migrations (stored for later backup creation)
1821
+ let classifiedMigrations = null;
1822
+ if (hasMigrations) {
1823
+ console.log(chalk.cyan("Analyzing migrations...\n"));
1824
+ classifiedMigrations = classifyMigrations(pendingMigrations, cwd, hashes, templates);
1825
+ printMigrationSummary(classifiedMigrations);
1826
+ // Hard-stop: pending rename/delete work from a breaking release requires --migrate.
1827
+ // Why: without --migrate, those entries are skipped and update()'s later path silently
1828
+ // bumps the version stamp, leaving old paths orphaned next to new templates. Force
1829
+ // explicit opt-in so the user can't half-migrate by accident.
1830
+ const pendingMigrationCount = classifiedMigrations.auto.length +
1831
+ classifiedMigrations.confirm.length +
1832
+ classifiedMigrations.conflict.length;
1833
+ if (pendingMigrationCount > 0 &&
1834
+ !options.migrate &&
1835
+ !options.dryRun &&
1836
+ cliVsProject > 0 &&
1837
+ projectVersion !== "unknown") {
1838
+ const gateMetadata = getMigrationMetadata(projectVersion, cliVersion);
1839
+ if (gateMetadata.breaking && gateMetadata.recommendMigrate) {
1840
+ console.log(chalk.bgRed.white.bold(" āœ– MIGRATION REQUIRED ") +
1841
+ chalk.red(` Breaking changes between ${projectVersion} → ${cliVersion} require --migrate.`));
1842
+ console.log("");
1843
+ console.log(chalk.yellow(` Run: atw update --migrate`));
1844
+ console.log("");
1845
+ console.log(chalk.gray(" Without --migrate, renamed/relocated files from breaking releases aren't moved,\n" +
1846
+ " leaving your project with stale paths alongside new templates.\n" +
1847
+ " Use --dry-run to preview what --migrate will do."));
1848
+ process.exit(1);
1849
+ }
1850
+ }
1851
+ // Soft hint: non-breaking migrations or projects that chose not to set recommendMigrate
1852
+ if (!options.migrate) {
1853
+ const autoCount = classifiedMigrations.auto.length;
1854
+ const confirmCount = classifiedMigrations.confirm.length;
1855
+ if (autoCount > 0 || confirmCount > 0) {
1856
+ console.log(chalk.gray(`Tip: Use --migrate to apply migrations (prompts for modified files).`));
1857
+ if (confirmCount > 0) {
1858
+ console.log(chalk.gray(` Use --migrate -f to force all, or --migrate -s to skip modified.\n`));
1859
+ }
1860
+ else {
1861
+ console.log("");
1862
+ }
1863
+ }
1864
+ }
1865
+ }
1866
+ // Print safe-file-delete summary (always shown, runs without --migrate)
1867
+ if (safeFileDeletes.length > 0) {
1868
+ printSafeFileDeleteSummary(safeFileDeletes);
1869
+ }
1870
+ // Analyze changes (pass hashes for modification detection)
1871
+ const changes = analyzeChanges(cwd, hashes, templates);
1872
+ const unchangedFileHashRepairs = collectUnchangedFileHashRepairs(changes, hashes);
1873
+ // Print summary
1874
+ printChangeSummary(changes);
1875
+ // First-time hash tracking hint
1876
+ if (isFirstHashTracking && changes.changedFiles.length > 0) {
1877
+ console.log(chalk.cyan("ā„¹ļø First update with hash tracking enabled."));
1878
+ console.log(chalk.gray(" Changed files shown above may not be actual user modifications."));
1879
+ console.log(chalk.gray(" After this update, hash tracking will accurately detect changes.\n"));
1880
+ }
1881
+ // Ensure project-root .gitattributes carries the journal merge=union rule.
1882
+ // Additive-only (see ensureGitattributes) — runs regardless of whether
1883
+ // other template files changed, so it must sit before the "nothing to do"
1884
+ // early-return below. Never touches disk in --dry-run.
1885
+ if (!options.dryRun) {
1886
+ ensureGitattributes(cwd);
1887
+ }
1888
+ // Check if there's anything to do
1889
+ const isUpgrade = cliVsProject > 0;
1890
+ const isDowngrade = cliVsProject < 0;
1891
+ const isSameVersion = cliVsProject === 0;
1892
+ // Check if we have pending migrations that need to be applied
1893
+ const hasPendingMigrations = options.migrate &&
1894
+ classifiedMigrations &&
1895
+ (classifiedMigrations.auto.length > 0 ||
1896
+ classifiedMigrations.confirm.length > 0);
1897
+ if (changes.newFiles.length === 0 &&
1898
+ changes.autoUpdateFiles.length === 0 &&
1899
+ changes.changedFiles.length === 0 &&
1900
+ !hasPendingMigrations &&
1901
+ !hasSafeDeletes) {
1902
+ // The "already up to date" exit still has to repair the receipt: this is
1903
+ // exactly the clean tree where every file is `unchanged`, so it is the run
1904
+ // where a wrong entry would otherwise be skipped again.
1905
+ if (!options.dryRun && unchangedFileHashRepairs.size > 0) {
1906
+ updateHashes(cwd, unchangedFileHashRepairs);
1907
+ }
1908
+ if (isSameVersion) {
1909
+ console.log(chalk.green("āœ“ Already up to date!"));
1910
+ }
1911
+ else {
1912
+ // Version changed but no file changes needed — still update the version stamp
1913
+ updateVersionFile(cwd);
1914
+ if (isUpgrade) {
1915
+ console.log(chalk.green(`āœ“ No file changes needed for ${projectVersion} → ${cliVersion}`));
1916
+ }
1917
+ else if (isDowngrade) {
1918
+ console.log(chalk.green(`āœ“ No file changes needed for ${projectVersion} → ${cliVersion} (downgrade)`));
1919
+ }
1920
+ }
1921
+ return;
1922
+ }
1923
+ // Show what this operation will do
1924
+ if (isUpgrade) {
1925
+ console.log(chalk.green(`This will UPGRADE: ${projectVersion} → ${cliVersion}\n`));
1926
+ }
1927
+ else if (isDowngrade) {
1928
+ console.log(chalk.red(`āš ļø This will DOWNGRADE: ${projectVersion} → ${cliVersion}\n`));
1929
+ }
1930
+ // Show breaking change warning before confirm
1931
+ if (cliVsProject > 0 && projectVersion !== "unknown") {
1932
+ const preConfirmMetadata = getMigrationMetadata(projectVersion, cliVersion);
1933
+ if (preConfirmMetadata.breaking) {
1934
+ console.log(chalk.cyan("═".repeat(60)));
1935
+ console.log(chalk.bgRed.white.bold(" āš ļø BREAKING CHANGES ") +
1936
+ chalk.red.bold(" Review the changes above carefully!"));
1937
+ if (preConfirmMetadata.changelog.length > 0) {
1938
+ console.log("");
1939
+ console.log(chalk.white(preConfirmMetadata.changelog[0]));
1940
+ }
1941
+ if (preConfirmMetadata.recommendMigrate && !options.migrate) {
1942
+ console.log("");
1943
+ console.log(chalk.bgGreen.black.bold(" šŸ’” RECOMMENDED ") +
1944
+ chalk.green.bold(" Run with --migrate to complete the migration"));
1945
+ }
1946
+ // Notice when update.skip is bypassed so user isn't surprised when
1947
+ // skipPaths-protected files get cleaned up during this breaking upgrade.
1948
+ if (breakingBypass && skipPaths.length > 0) {
1949
+ const willBypass = safeFileDeletes.filter((c) => c.action === "delete" &&
1950
+ skipPaths.some((skip) => c.item.from === skip ||
1951
+ c.item.from.startsWith(skip.endsWith("/") ? skip : skip + "/")));
1952
+ if (willBypass.length > 0) {
1953
+ console.log("");
1954
+ console.log(chalk.bgYellow.black.bold(" ⚠ update.skip BYPASSED ") +
1955
+ chalk.yellow.bold(` Breaking release — ${willBypass.length.toString()} file(s) under your update.skip paths will be cleaned up.`));
1956
+ console.log(chalk.gray(" Hash-verified: only files matching known ATW templates are deleted. Your local customizations (hash mismatch) are still preserved."));
1957
+ }
1958
+ }
1959
+ console.log(chalk.cyan("═".repeat(60)));
1960
+ console.log("");
1961
+ }
1962
+ }
1963
+ // Dry run mode
1964
+ if (options.dryRun) {
1965
+ console.log(chalk.gray("[Dry run] No changes made."));
1966
+ return;
1967
+ }
1968
+ // Batch-resolution flags are explicit consent for non-interactive runs.
1969
+ // Prompting here breaks CI and `node ... update --force --migrate` smoke tests.
1970
+ if (!options.force && !options.skipAll && !options.createNew) {
1971
+ const { proceed } = await inquirer.prompt([
1972
+ {
1973
+ type: "confirm",
1974
+ name: "proceed",
1975
+ message: "Proceed?",
1976
+ default: true,
1977
+ },
1978
+ ]);
1979
+ if (!proceed) {
1980
+ console.log(chalk.yellow("Update cancelled."));
1981
+ return;
1982
+ }
1983
+ }
1984
+ // Create complete backup of all managed platform/workflow directories
1985
+ const backupDir = createFullBackup(cwd);
1986
+ if (backupDir) {
1987
+ console.log(chalk.gray(`\nBackup created: ${path.relative(cwd, backupDir)}/`));
1988
+ }
1989
+ // Execute migrations if --migrate flag is set
1990
+ if (options.migrate && classifiedMigrations) {
1991
+ const migrationResult = await executeMigrations(classifiedMigrations, cwd, {
1992
+ force: options.force,
1993
+ skipAll: options.skipAll,
1994
+ }, templates);
1995
+ printMigrationResult(migrationResult);
1996
+ // Hardcoded: Rename traces-*.md to journal-*.md in workspace directories
1997
+ // Why hardcoded: The migration system only supports fixed path renames, not pattern-based.
1998
+ // traces-*.md files are in .atw/workspace/{developer}/ with variable developer names
1999
+ // and variable file numbers (traces-1.md, traces-2.md, etc.), so we can't enumerate them
2000
+ // in the migration manifest. This is a one-time migration for the journal naming redesign.
2001
+ const workspaceDir = path.join(cwd, PATHS.WORKSPACE);
2002
+ const { renamed: journalRenamed, skipped: journalSkipped } = renameTracesToJournal(workspaceDir);
2003
+ if (journalRenamed > 0) {
2004
+ console.log(chalk.cyan(`Renamed ${journalRenamed} traces file(s) to journal`));
2005
+ }
2006
+ for (const oldPath of journalSkipped) {
2007
+ console.warn(chalk.yellow(`Kept ${path.relative(cwd, oldPath)}: its journal target already exists`));
2008
+ }
2009
+ }
2010
+ // Execute safe-file-delete (after backup, before template writes)
2011
+ let safeDeleted = 0;
2012
+ if (hasSafeDeletes) {
2013
+ safeDeleted = executeSafeFileDeletes(safeFileDeletes, cwd);
2014
+ if (safeDeleted > 0) {
2015
+ console.log(chalk.cyan(`\nCleaned up ${safeDeleted} deprecated command file(s)`));
2016
+ }
2017
+ }
2018
+ // Track results
2019
+ let added = 0;
2020
+ let autoUpdated = 0;
2021
+ let updated = 0;
2022
+ let skipped = 0;
2023
+ let createdNew = 0;
2024
+ // Add new files
2025
+ if (changes.newFiles.length > 0) {
2026
+ console.log(chalk.blue("\nAdding new files..."));
2027
+ for (const file of changes.newFiles) {
2028
+ const dir = path.dirname(file.path);
2029
+ fs.mkdirSync(dir, { recursive: true });
2030
+ fs.writeFileSync(file.path, file.newContent);
2031
+ // Make scripts executable
2032
+ if (file.relativePath.endsWith(".sh") ||
2033
+ file.relativePath.endsWith(".py")) {
2034
+ fs.chmodSync(file.path, "755");
2035
+ }
2036
+ console.log(chalk.green(` + ${file.relativePath}`));
2037
+ added++;
2038
+ }
2039
+ }
2040
+ // Auto-update files (template updated, user didn't modify)
2041
+ if (changes.autoUpdateFiles.length > 0) {
2042
+ console.log(chalk.blue("\nAuto-updating template files..."));
2043
+ for (const file of changes.autoUpdateFiles) {
2044
+ fs.writeFileSync(file.path, file.newContent);
2045
+ // Make scripts executable
2046
+ if (file.relativePath.endsWith(".sh") ||
2047
+ file.relativePath.endsWith(".py")) {
2048
+ fs.chmodSync(file.path, "755");
2049
+ }
2050
+ console.log(chalk.cyan(` ↑ ${file.relativePath}`));
2051
+ autoUpdated++;
2052
+ }
2053
+ }
2054
+ // Handle changed files
2055
+ if (changes.changedFiles.length > 0) {
2056
+ console.log(chalk.blue("\n--- Resolving conflicts ---\n"));
2057
+ const applyToAll = { action: null };
2058
+ for (const file of changes.changedFiles) {
2059
+ const action = await promptConflictResolution(file, options, applyToAll);
2060
+ if (action === "overwrite") {
2061
+ fs.writeFileSync(file.path, file.newContent);
2062
+ if (file.relativePath.endsWith(".sh") ||
2063
+ file.relativePath.endsWith(".py")) {
2064
+ fs.chmodSync(file.path, "755");
2065
+ }
2066
+ console.log(chalk.yellow(` āœ“ Overwritten: ${file.relativePath}`));
2067
+ updated++;
2068
+ }
2069
+ else if (action === "create-new") {
2070
+ const newPath = file.path + ".new";
2071
+ fs.writeFileSync(newPath, file.newContent);
2072
+ console.log(chalk.blue(` āœ“ Created: ${file.relativePath}.new`));
2073
+ createdNew++;
2074
+ }
2075
+ else {
2076
+ console.log(chalk.gray(` ā—‹ Skipped: ${file.relativePath}`));
2077
+ skipped++;
2078
+ }
2079
+ }
2080
+ }
2081
+ // Append additive config.yaml sections introduced between versions.
2082
+ // Sentinel-gated, so users keep their customizations and re-running update
2083
+ // on already-migrated files is a no-op. Skipped on unknown / downgrade.
2084
+ let configSectionsAppended = 0;
2085
+ if (cliVsProject > 0 && projectVersion !== "unknown") {
2086
+ const sectionEntries = getConfigSectionsAddedBetween(projectVersion, cliVersion);
2087
+ if (sectionEntries.length > 0) {
2088
+ const { appended } = applyConfigSectionsAdded(sectionEntries, cwd, templates);
2089
+ configSectionsAppended = appended;
2090
+ }
2091
+ }
2092
+ // Update version file
2093
+ updateVersionFile(cwd);
2094
+ // Update template hashes for new, auto-updated, and overwritten files
2095
+ const filesToHash = new Map(unchangedFileHashRepairs);
2096
+ for (const file of changes.newFiles) {
2097
+ filesToHash.set(file.relativePath, file.newContent);
2098
+ }
2099
+ // Auto-updated files always get new hash
2100
+ for (const file of changes.autoUpdateFiles) {
2101
+ filesToHash.set(file.relativePath, file.newContent);
2102
+ }
2103
+ // Only hash overwritten files (not skipped or .new copies)
2104
+ for (const file of changes.changedFiles) {
2105
+ const fullPath = path.join(cwd, file.relativePath);
2106
+ if (fs.existsSync(fullPath)) {
2107
+ const content = fs.readFileSync(fullPath, "utf-8");
2108
+ if (content === file.newContent) {
2109
+ filesToHash.set(file.relativePath, file.newContent);
2110
+ }
2111
+ }
2112
+ }
2113
+ if (filesToHash.size > 0) {
2114
+ updateHashes(cwd, filesToHash);
2115
+ }
2116
+ // Print summary
2117
+ console.log(chalk.cyan("\n--- Summary ---\n"));
2118
+ if (added > 0) {
2119
+ console.log(` Added: ${added} file(s)`);
2120
+ }
2121
+ if (autoUpdated > 0) {
2122
+ console.log(` Auto-updated: ${autoUpdated} file(s)`);
2123
+ }
2124
+ if (updated > 0) {
2125
+ console.log(` Updated: ${updated} file(s)`);
2126
+ }
2127
+ if (skipped > 0) {
2128
+ console.log(` Skipped: ${skipped} file(s)`);
2129
+ }
2130
+ if (createdNew > 0) {
2131
+ console.log(` Created .new copies: ${createdNew} file(s)`);
2132
+ }
2133
+ if (safeDeleted > 0) {
2134
+ console.log(` Cleaned up: ${safeDeleted} deprecated file(s)`);
2135
+ }
2136
+ if (configSectionsAppended > 0) {
2137
+ console.log(` Config sections added: ${configSectionsAppended}`);
2138
+ }
2139
+ if (backupDir) {
2140
+ console.log(` Backup: ${path.relative(cwd, backupDir)}/`);
2141
+ }
2142
+ const actionWord = isDowngrade ? "Downgrade" : "Update";
2143
+ console.log(chalk.green(`\nāœ… ${actionWord} complete! (${projectVersion} → ${cliVersion})`));
2144
+ if (createdNew > 0) {
2145
+ console.log(chalk.gray("\nTip: Review .new files and merge changes manually if needed."));
2146
+ }
2147
+ // Create migration task if there are breaking changes with migration guides
2148
+ if (cliVsProject > 0 && projectVersion !== "unknown") {
2149
+ const metadata = getMigrationMetadata(projectVersion, cliVersion);
2150
+ if (metadata.breaking && metadata.migrationGuides.length > 0) {
2151
+ // Create task directory
2152
+ const today = new Date();
2153
+ const monthDay = `${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
2154
+ const taskSlug = `migrate-to-${cliVersion}`;
2155
+ const taskDirName = `${monthDay}-${taskSlug}`;
2156
+ const tasksDir = path.join(cwd, DIR_NAMES.WORKFLOW, DIR_NAMES.TASKS);
2157
+ const taskDir = path.join(tasksDir, taskDirName);
2158
+ // Check if task already exists
2159
+ if (!fs.existsSync(taskDir)) {
2160
+ fs.mkdirSync(taskDir, { recursive: true });
2161
+ // Get current developer for assignee.
2162
+ // `.developer` is a key=value file (written by init_developer.py):
2163
+ // name=<developer-name>
2164
+ // initialized_at=<iso8601>
2165
+ // Reading it raw and .trim()-ing embeds the entire file contents
2166
+ // (including the `name=` prefix and the `initialized_at` line) into
2167
+ // the assignee field, producing bogus assignees like
2168
+ // "name=alex\ninitialized_at=2026-09-01T23:41:21.978312" that
2169
+ // later break session-start task rendering.
2170
+ const developerFile = path.join(cwd, DIR_NAMES.WORKFLOW, ".developer");
2171
+ let currentDeveloper = "unknown";
2172
+ if (fs.existsSync(developerFile)) {
2173
+ const raw = fs.readFileSync(developerFile, "utf-8");
2174
+ const nameMatch = raw.match(/^\s*name\s*=\s*(.+?)\s*$/m);
2175
+ if (nameMatch) {
2176
+ currentDeveloper = nameMatch[1];
2177
+ }
2178
+ }
2179
+ // Build task.json — canonical 24-field shape via shared factory.
2180
+ const taskTitle = `Migrate to v${cliVersion}`;
2181
+ const todayStr = today.toISOString().split("T")[0];
2182
+ const taskJson = emptyTaskJson({
2183
+ id: taskSlug,
2184
+ name: taskSlug,
2185
+ title: taskTitle,
2186
+ description: `Breaking change migration from v${projectVersion} to v${cliVersion}`,
2187
+ status: "discover",
2188
+ scope: "migration",
2189
+ priority: "P1",
2190
+ creator: "atw-update",
2191
+ assignee: currentDeveloper,
2192
+ createdAt: todayStr,
2193
+ });
2194
+ // Write task.json
2195
+ const taskJsonPath = path.join(taskDir, "task.json");
2196
+ fs.writeFileSync(taskJsonPath, JSON.stringify(taskJson, null, 2));
2197
+ // Build PRD content
2198
+ let prdContent = `# Migration Task: Upgrade to v${cliVersion}\n\n`;
2199
+ prdContent += `**Created**: ${todayStr}\n`;
2200
+ prdContent += `**From Version**: ${projectVersion}\n`;
2201
+ prdContent += `**To Version**: ${cliVersion}\n`;
2202
+ prdContent += `**Assignee**: ${currentDeveloper}\n\n`;
2203
+ prdContent += `## Status\n\n- [ ] Review migration guide\n- [ ] Update custom files\n- [ ] Run \`atw update --migrate\`\n- [ ] Test workflows\n\n`;
2204
+ for (const { version, guide, aiInstructions, } of metadata.migrationGuides) {
2205
+ prdContent += `---\n\n## v${version} Migration Guide\n\n`;
2206
+ prdContent += guide;
2207
+ prdContent += "\n\n";
2208
+ if (aiInstructions) {
2209
+ prdContent += `### AI Assistant Instructions\n\n`;
2210
+ prdContent += `When helping with this migration:\n\n`;
2211
+ prdContent += aiInstructions;
2212
+ prdContent += "\n\n";
2213
+ }
2214
+ }
2215
+ // Write PRD
2216
+ const prdPath = path.join(taskDir, "prd.md");
2217
+ fs.writeFileSync(prdPath, prdContent);
2218
+ console.log("");
2219
+ console.log(chalk.bgCyan.black.bold(" šŸ“‹ MIGRATION TASK CREATED "));
2220
+ console.log(chalk.cyan(`A task has been created to help you complete the migration:`));
2221
+ console.log(chalk.white(` ${DIR_NAMES.WORKFLOW}/${DIR_NAMES.TASKS}/${taskDirName}/`));
2222
+ console.log("");
2223
+ console.log(chalk.gray("Use AI to help: Ask Claude/Cursor to read the task and fix your custom files."));
2224
+ }
2225
+ }
2226
+ }
2227
+ // Display breaking change warnings at the very end (so they don't scroll off screen)
2228
+ if (cliVsProject > 0 && projectVersion !== "unknown") {
2229
+ const finalMetadata = getMigrationMetadata(projectVersion, cliVersion);
2230
+ if (finalMetadata.breaking || finalMetadata.changelog.length > 0) {
2231
+ console.log("");
2232
+ console.log(chalk.cyan("═".repeat(60)));
2233
+ if (finalMetadata.breaking) {
2234
+ console.log(chalk.bgRed.white.bold(" āš ļø BREAKING CHANGES ") +
2235
+ chalk.red.bold(" This update contains breaking changes!"));
2236
+ console.log("");
2237
+ }
2238
+ if (finalMetadata.changelog.length > 0) {
2239
+ console.log(chalk.cyan.bold("šŸ“‹ What's Changed:"));
2240
+ for (const entry of finalMetadata.changelog) {
2241
+ console.log(chalk.white(` ${entry}`));
2242
+ }
2243
+ console.log("");
2244
+ }
2245
+ if (finalMetadata.recommendMigrate && !options.migrate) {
2246
+ console.log(chalk.bgGreen.black.bold(" šŸ’” RECOMMENDED ") +
2247
+ chalk.green.bold(" Run with --migrate to complete the migration"));
2248
+ console.log(chalk.gray(" This will remove legacy files and apply all changes."));
2249
+ console.log("");
2250
+ }
2251
+ console.log(chalk.cyan("═".repeat(60)));
2252
+ }
2253
+ }
2254
+ }
2255
+ //# sourceMappingURL=update.js.map