@blxzer/cursor-trellis 0.1.0

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