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