@stackmemoryai/stackmemory 0.2.4 → 0.2.7

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 (331) hide show
  1. package/README.md +353 -83
  2. package/dist/index.js +382 -0
  3. package/dist/scripts/cancel-duplicate-tasks.d.ts +7 -0
  4. package/dist/scripts/cancel-duplicate-tasks.d.ts.map +1 -0
  5. package/dist/scripts/cancel-duplicate-tasks.js +171 -0
  6. package/dist/scripts/cancel-duplicate-tasks.js.map +1 -0
  7. package/dist/scripts/list-linear-tasks.d.ts +6 -0
  8. package/dist/scripts/list-linear-tasks.d.ts.map +1 -0
  9. package/dist/scripts/list-linear-tasks.js +122 -0
  10. package/dist/scripts/list-linear-tasks.js.map +1 -0
  11. package/dist/scripts/merge-linear-duplicates-safe.d.ts +7 -0
  12. package/dist/scripts/merge-linear-duplicates-safe.d.ts.map +1 -0
  13. package/dist/scripts/merge-linear-duplicates-safe.js +265 -0
  14. package/dist/scripts/merge-linear-duplicates-safe.js.map +1 -0
  15. package/dist/scripts/merge-linear-duplicates.d.ts +7 -0
  16. package/dist/scripts/merge-linear-duplicates.d.ts.map +1 -0
  17. package/dist/scripts/merge-linear-duplicates.js +126 -0
  18. package/dist/scripts/merge-linear-duplicates.js.map +1 -0
  19. package/dist/scripts/show-linear-summary.d.ts +6 -0
  20. package/dist/scripts/show-linear-summary.d.ts.map +1 -0
  21. package/dist/scripts/show-linear-summary.js +117 -0
  22. package/dist/scripts/show-linear-summary.js.map +1 -0
  23. package/dist/src/analytics/api/analytics-api.d.ts +24 -0
  24. package/dist/src/analytics/api/analytics-api.d.ts.map +1 -0
  25. package/dist/src/analytics/api/analytics-api.js +279 -0
  26. package/dist/src/analytics/api/analytics-api.js.map +1 -0
  27. package/dist/src/analytics/core/analytics-service.d.ts +23 -0
  28. package/dist/src/analytics/core/analytics-service.d.ts.map +1 -0
  29. package/dist/src/analytics/core/analytics-service.js +160 -0
  30. package/dist/src/analytics/core/analytics-service.js.map +1 -0
  31. package/dist/src/analytics/index.d.ts +12 -0
  32. package/dist/src/analytics/index.d.ts.map +1 -0
  33. package/dist/src/analytics/index.js +11 -0
  34. package/dist/src/analytics/index.js.map +1 -0
  35. package/dist/src/analytics/queries/metrics-queries.d.ts +11 -0
  36. package/dist/src/analytics/queries/metrics-queries.d.ts.map +1 -0
  37. package/dist/src/analytics/queries/metrics-queries.js +179 -0
  38. package/dist/src/analytics/queries/metrics-queries.js.map +1 -0
  39. package/dist/src/analytics/types/metrics.d.ts +60 -0
  40. package/dist/src/analytics/types/metrics.d.ts.map +1 -0
  41. package/dist/src/analytics/types/metrics.js +2 -0
  42. package/dist/src/analytics/types/metrics.js.map +1 -0
  43. package/dist/src/cli/__tests__/index.test.d.ts +5 -0
  44. package/dist/src/cli/__tests__/index.test.d.ts.map +1 -0
  45. package/dist/src/cli/__tests__/index.test.js +726 -0
  46. package/dist/src/cli/__tests__/index.test.js.map +1 -0
  47. package/dist/src/cli/analytics-viewer.d.ts +3 -0
  48. package/dist/src/cli/analytics-viewer.d.ts.map +1 -0
  49. package/dist/src/cli/analytics-viewer.js +89 -0
  50. package/dist/src/cli/analytics-viewer.js.map +1 -0
  51. package/dist/src/cli/auto-detect.d.ts +61 -0
  52. package/dist/src/cli/auto-detect.d.ts.map +1 -0
  53. package/dist/src/cli/auto-detect.js +350 -0
  54. package/dist/src/cli/auto-detect.js.map +1 -0
  55. package/dist/src/cli/browser-test.d.ts +6 -0
  56. package/dist/src/cli/browser-test.d.ts.map +1 -0
  57. package/dist/src/cli/browser-test.js +32 -0
  58. package/dist/src/cli/browser-test.js.map +1 -0
  59. package/dist/src/cli/claude-sm.d.ts +7 -0
  60. package/dist/src/cli/claude-sm.d.ts.map +1 -0
  61. package/dist/src/cli/claude-sm.js +357 -0
  62. package/dist/src/cli/claude-sm.js.map +1 -0
  63. package/dist/src/cli/cli.js +157 -0
  64. package/dist/src/cli/cli.js.map +1 -1
  65. package/dist/src/cli/commands/context.d.ts +7 -0
  66. package/dist/src/cli/commands/context.d.ts.map +1 -0
  67. package/dist/src/cli/commands/context.js +365 -0
  68. package/dist/src/cli/commands/context.js.map +1 -0
  69. package/dist/src/cli/commands/linear-test.d.ts +6 -0
  70. package/dist/src/cli/commands/linear-test.d.ts.map +1 -0
  71. package/dist/src/cli/commands/linear-test.js +123 -0
  72. package/dist/src/cli/commands/linear-test.js.map +1 -0
  73. package/dist/src/cli/commands/linear.d.ts +6 -0
  74. package/dist/src/cli/commands/linear.d.ts.map +1 -0
  75. package/dist/src/cli/commands/linear.js +317 -0
  76. package/dist/src/cli/commands/linear.js.map +1 -0
  77. package/dist/src/cli/commands/log.d.ts +7 -0
  78. package/dist/src/cli/commands/log.d.ts.map +1 -0
  79. package/dist/src/cli/commands/log.js +168 -0
  80. package/dist/src/cli/commands/log.js.map +1 -0
  81. package/dist/src/cli/commands/onboard.d.ts +8 -0
  82. package/dist/src/cli/commands/onboard.d.ts.map +1 -0
  83. package/dist/src/cli/commands/onboard.js +363 -0
  84. package/dist/src/cli/commands/onboard.js.map +1 -0
  85. package/dist/src/cli/commands/projects.d.ts +8 -0
  86. package/dist/src/cli/commands/projects.d.ts.map +1 -0
  87. package/dist/src/cli/commands/projects.js +220 -0
  88. package/dist/src/cli/commands/projects.js.map +1 -0
  89. package/dist/src/cli/commands/search.d.ts +7 -0
  90. package/dist/src/cli/commands/search.d.ts.map +1 -0
  91. package/dist/src/cli/commands/search.js +162 -0
  92. package/dist/src/cli/commands/search.js.map +1 -0
  93. package/dist/src/cli/commands/session.d.ts +7 -0
  94. package/dist/src/cli/commands/session.d.ts.map +1 -0
  95. package/dist/src/cli/commands/session.js +222 -0
  96. package/dist/src/cli/commands/session.js.map +1 -0
  97. package/dist/src/cli/commands/tasks.d.ts +7 -0
  98. package/dist/src/cli/commands/tasks.d.ts.map +1 -0
  99. package/dist/src/cli/commands/tasks.js +229 -0
  100. package/dist/src/cli/commands/tasks.js.map +1 -0
  101. package/dist/src/cli/commands/webhook.d.ts +3 -0
  102. package/dist/src/cli/commands/webhook.d.ts.map +1 -0
  103. package/dist/src/cli/commands/webhook.js +157 -0
  104. package/dist/src/cli/commands/webhook.js.map +1 -0
  105. package/dist/src/cli/commands/worktree.d.ts +8 -0
  106. package/dist/src/cli/commands/worktree.d.ts.map +1 -0
  107. package/dist/src/cli/commands/worktree.js +339 -0
  108. package/dist/src/cli/commands/worktree.js.map +1 -0
  109. package/dist/src/cli/index.d.ts +8 -0
  110. package/dist/src/cli/index.d.ts.map +1 -0
  111. package/dist/src/cli/index.js +944 -0
  112. package/dist/src/cli/index.js.map +1 -0
  113. package/dist/src/cli/project-commands.d.ts +8 -0
  114. package/dist/src/cli/project-commands.d.ts.map +1 -0
  115. package/dist/src/cli/project-commands.js +212 -0
  116. package/dist/src/cli/project-commands.js.map +1 -0
  117. package/dist/src/cli/utils/viewer.d.ts +3 -0
  118. package/dist/src/cli/utils/viewer.d.ts.map +1 -0
  119. package/dist/src/cli/utils/viewer.js +91 -0
  120. package/dist/src/cli/utils/viewer.js.map +1 -0
  121. package/dist/src/core/context/__tests__/frame-manager.test.d.ts +5 -0
  122. package/dist/src/core/context/__tests__/frame-manager.test.d.ts.map +1 -0
  123. package/dist/src/core/context/__tests__/frame-manager.test.js +892 -0
  124. package/dist/src/core/context/__tests__/frame-manager.test.js.map +1 -0
  125. package/dist/src/core/context/auto-context.d.ts +22 -0
  126. package/dist/src/core/context/auto-context.d.ts.map +1 -0
  127. package/dist/src/core/context/auto-context.js +77 -0
  128. package/dist/src/core/context/auto-context.js.map +1 -0
  129. package/dist/src/core/context/frame-manager.d.ts +110 -0
  130. package/dist/src/core/context/frame-manager.d.ts.map +1 -0
  131. package/dist/src/core/context/frame-manager.js +593 -0
  132. package/dist/src/core/context/frame-manager.js.map +1 -0
  133. package/dist/src/core/errors/__tests__/error-handling.test.d.ts +5 -0
  134. package/dist/src/core/errors/__tests__/error-handling.test.d.ts.map +1 -0
  135. package/dist/src/core/errors/__tests__/error-handling.test.js +239 -0
  136. package/dist/src/core/errors/__tests__/error-handling.test.js.map +1 -0
  137. package/dist/src/core/errors/index.d.ts +135 -0
  138. package/dist/src/core/errors/index.d.ts.map +1 -0
  139. package/dist/src/core/errors/index.js +274 -0
  140. package/dist/src/core/errors/index.js.map +1 -0
  141. package/dist/src/core/errors/recovery.d.ts +86 -0
  142. package/dist/src/core/errors/recovery.d.ts.map +1 -0
  143. package/dist/src/core/errors/recovery.js +274 -0
  144. package/dist/src/core/errors/recovery.js.map +1 -0
  145. package/dist/src/core/logger.test.js +1 -1
  146. package/dist/src/core/logger.test.js.map +1 -1
  147. package/dist/src/core/monitoring/error-handler.d.ts +46 -0
  148. package/dist/src/core/monitoring/error-handler.d.ts.map +1 -0
  149. package/dist/src/core/monitoring/error-handler.js +212 -0
  150. package/dist/src/core/monitoring/error-handler.js.map +1 -0
  151. package/dist/src/core/monitoring/logger.d.ts +24 -0
  152. package/dist/src/core/monitoring/logger.d.ts.map +1 -0
  153. package/dist/src/core/monitoring/logger.js +121 -0
  154. package/dist/src/core/monitoring/logger.js.map +1 -0
  155. package/dist/src/core/monitoring/metrics.d.ts +7 -0
  156. package/dist/src/core/monitoring/metrics.d.ts.map +1 -0
  157. package/dist/src/core/monitoring/metrics.js +13 -0
  158. package/dist/src/core/monitoring/metrics.js.map +1 -0
  159. package/dist/src/core/monitoring/progress-tracker.d.ts +95 -0
  160. package/dist/src/core/monitoring/progress-tracker.d.ts.map +1 -0
  161. package/dist/src/core/monitoring/progress-tracker.js +178 -0
  162. package/dist/src/core/monitoring/progress-tracker.js.map +1 -0
  163. package/dist/src/core/project-manager.d.ts +130 -0
  164. package/dist/src/core/project-manager.d.ts.map +1 -0
  165. package/dist/src/core/project-manager.js +582 -0
  166. package/dist/src/core/project-manager.js.map +1 -0
  167. package/dist/src/core/projects/project-manager.d.ts +130 -0
  168. package/dist/src/core/projects/project-manager.d.ts.map +1 -0
  169. package/dist/src/core/projects/project-manager.js +709 -0
  170. package/dist/src/core/projects/project-manager.js.map +1 -0
  171. package/dist/src/core/session/index.d.ts +2 -0
  172. package/dist/src/core/session/index.d.ts.map +1 -0
  173. package/dist/src/core/session/index.js +2 -0
  174. package/dist/src/core/session/index.js.map +1 -0
  175. package/dist/src/core/session/session-manager.d.ts +69 -0
  176. package/dist/src/core/session/session-manager.d.ts.map +1 -0
  177. package/dist/src/core/session/session-manager.js +311 -0
  178. package/dist/src/core/session/session-manager.js.map +1 -0
  179. package/dist/src/core/utils/update-checker.d.ts +38 -0
  180. package/dist/src/core/utils/update-checker.d.ts.map +1 -0
  181. package/dist/src/core/utils/update-checker.js +213 -0
  182. package/dist/src/core/utils/update-checker.js.map +1 -0
  183. package/dist/src/core/worktree/worktree-manager.d.ts +110 -0
  184. package/dist/src/core/worktree/worktree-manager.d.ts.map +1 -0
  185. package/dist/src/core/worktree/worktree-manager.js +456 -0
  186. package/dist/src/core/worktree/worktree-manager.js.map +1 -0
  187. package/dist/src/features/analytics/api/analytics-api.d.ts +24 -0
  188. package/dist/src/features/analytics/api/analytics-api.d.ts.map +1 -0
  189. package/dist/src/features/analytics/api/analytics-api.js +289 -0
  190. package/dist/src/features/analytics/api/analytics-api.js.map +1 -0
  191. package/dist/src/features/analytics/core/analytics-service.d.ts +29 -0
  192. package/dist/src/features/analytics/core/analytics-service.d.ts.map +1 -0
  193. package/dist/src/features/analytics/core/analytics-service.js +275 -0
  194. package/dist/src/features/analytics/core/analytics-service.js.map +1 -0
  195. package/dist/src/features/analytics/index.d.ts +12 -0
  196. package/dist/src/features/analytics/index.d.ts.map +1 -0
  197. package/dist/src/features/analytics/index.js +11 -0
  198. package/dist/src/features/analytics/index.js.map +1 -0
  199. package/dist/src/features/analytics/queries/metrics-queries.d.ts +11 -0
  200. package/dist/src/features/analytics/queries/metrics-queries.d.ts.map +1 -0
  201. package/dist/src/features/analytics/queries/metrics-queries.js +240 -0
  202. package/dist/src/features/analytics/queries/metrics-queries.js.map +1 -0
  203. package/dist/src/features/analytics/types/metrics.d.ts +60 -0
  204. package/dist/src/features/analytics/types/metrics.d.ts.map +1 -0
  205. package/dist/src/features/analytics/types/metrics.js +2 -0
  206. package/dist/src/features/analytics/types/metrics.js.map +1 -0
  207. package/dist/src/features/browser/browser-mcp.d.ts +94 -0
  208. package/dist/src/features/browser/browser-mcp.d.ts.map +1 -0
  209. package/dist/src/features/browser/browser-mcp.js +459 -0
  210. package/dist/src/features/browser/browser-mcp.js.map +1 -0
  211. package/dist/src/features/tasks/__tests__/pebbles-task-store.test.d.ts +5 -0
  212. package/dist/src/features/tasks/__tests__/pebbles-task-store.test.d.ts.map +1 -0
  213. package/dist/src/features/tasks/__tests__/pebbles-task-store.test.js +712 -0
  214. package/dist/src/features/tasks/__tests__/pebbles-task-store.test.js.map +1 -0
  215. package/dist/src/features/tasks/pebbles-task-store.d.ts +121 -0
  216. package/dist/src/features/tasks/pebbles-task-store.d.ts.map +1 -0
  217. package/dist/src/features/tasks/pebbles-task-store.js +493 -0
  218. package/dist/src/features/tasks/pebbles-task-store.js.map +1 -0
  219. package/dist/src/features/tasks/task-aware-context.d.ts +103 -0
  220. package/dist/src/features/tasks/task-aware-context.d.ts.map +1 -0
  221. package/dist/src/features/tasks/task-aware-context.js +412 -0
  222. package/dist/src/features/tasks/task-aware-context.js.map +1 -0
  223. package/dist/src/index.d.ts +4 -4
  224. package/dist/src/index.d.ts.map +1 -1
  225. package/dist/src/index.js +4 -4
  226. package/dist/src/index.js.map +1 -1
  227. package/dist/src/integrations/browser-mcp.d.ts +94 -0
  228. package/dist/src/integrations/browser-mcp.d.ts.map +1 -0
  229. package/dist/src/integrations/browser-mcp.js +431 -0
  230. package/dist/src/integrations/browser-mcp.js.map +1 -0
  231. package/dist/src/integrations/linear/__tests__/auth.test.d.ts +5 -0
  232. package/dist/src/integrations/linear/__tests__/auth.test.d.ts.map +1 -0
  233. package/dist/src/integrations/linear/__tests__/auth.test.js +517 -0
  234. package/dist/src/integrations/linear/__tests__/auth.test.js.map +1 -0
  235. package/dist/src/integrations/linear/__tests__/sync-service.test.d.ts +5 -0
  236. package/dist/src/integrations/linear/__tests__/sync-service.test.d.ts.map +1 -0
  237. package/dist/src/integrations/linear/__tests__/sync-service.test.js +700 -0
  238. package/dist/src/integrations/linear/__tests__/sync-service.test.js.map +1 -0
  239. package/dist/src/integrations/linear/auth.d.ts +99 -0
  240. package/dist/src/integrations/linear/auth.d.ts.map +1 -0
  241. package/dist/src/integrations/linear/auth.js +319 -0
  242. package/dist/src/integrations/linear/auth.js.map +1 -0
  243. package/dist/src/integrations/linear/auto-sync.d.ts +77 -0
  244. package/dist/src/integrations/linear/auto-sync.d.ts.map +1 -0
  245. package/dist/src/integrations/linear/auto-sync.js +268 -0
  246. package/dist/src/integrations/linear/auto-sync.js.map +1 -0
  247. package/dist/src/integrations/linear/client.d.ts +113 -0
  248. package/dist/src/integrations/linear/client.d.ts.map +1 -0
  249. package/dist/src/integrations/linear/client.js +364 -0
  250. package/dist/src/integrations/linear/client.js.map +1 -0
  251. package/dist/src/integrations/linear/config.d.ts +51 -0
  252. package/dist/src/integrations/linear/config.d.ts.map +1 -0
  253. package/dist/src/integrations/linear/config.js +103 -0
  254. package/dist/src/integrations/linear/config.js.map +1 -0
  255. package/dist/src/integrations/linear/sync-service.d.ts +25 -0
  256. package/dist/src/integrations/linear/sync-service.d.ts.map +1 -0
  257. package/dist/src/integrations/linear/sync-service.js +198 -0
  258. package/dist/src/integrations/linear/sync-service.js.map +1 -0
  259. package/dist/src/integrations/linear/sync.d.ts +119 -0
  260. package/dist/src/integrations/linear/sync.d.ts.map +1 -0
  261. package/dist/src/integrations/linear/sync.js +538 -0
  262. package/dist/src/integrations/linear/sync.js.map +1 -0
  263. package/dist/src/integrations/linear/types.d.ts +75 -0
  264. package/dist/src/integrations/linear/types.d.ts.map +1 -0
  265. package/dist/src/integrations/linear/types.js +2 -0
  266. package/dist/src/integrations/linear/types.js.map +1 -0
  267. package/dist/src/integrations/linear/webhook-server.d.ts +32 -0
  268. package/dist/src/integrations/linear/webhook-server.d.ts.map +1 -0
  269. package/dist/src/integrations/linear/webhook-server.js +188 -0
  270. package/dist/src/integrations/linear/webhook-server.js.map +1 -0
  271. package/dist/src/integrations/linear/webhook.d.ts +95 -0
  272. package/dist/src/integrations/linear/webhook.d.ts.map +1 -0
  273. package/dist/src/integrations/linear/webhook.js +204 -0
  274. package/dist/src/integrations/linear/webhook.js.map +1 -0
  275. package/dist/src/integrations/mcp/__tests__/server.test.d.ts +5 -0
  276. package/dist/src/integrations/mcp/__tests__/server.test.d.ts.map +1 -0
  277. package/dist/src/integrations/mcp/__tests__/server.test.js +790 -0
  278. package/dist/src/integrations/mcp/__tests__/server.test.js.map +1 -0
  279. package/dist/src/integrations/mcp/server.d.ts +46 -0
  280. package/dist/src/integrations/mcp/server.d.ts.map +1 -0
  281. package/dist/src/integrations/mcp/server.js +1264 -0
  282. package/dist/src/integrations/mcp/server.js.map +1 -0
  283. package/dist/src/mcp/mcp-server.d.ts +1 -0
  284. package/dist/src/mcp/mcp-server.d.ts.map +1 -1
  285. package/dist/src/mcp/mcp-server.js +11 -0
  286. package/dist/src/mcp/mcp-server.js.map +1 -1
  287. package/dist/src/railway/index.d.ts +7 -0
  288. package/dist/src/railway/index.d.ts.map +1 -0
  289. package/dist/src/railway/index.js +401 -0
  290. package/dist/src/railway/index.js.map +1 -0
  291. package/dist/src/runway/auth/auth-middleware.d.ts +66 -0
  292. package/dist/src/runway/auth/auth-middleware.d.ts.map +1 -0
  293. package/dist/src/runway/auth/auth-middleware.js +337 -0
  294. package/dist/src/runway/auth/auth-middleware.js.map +1 -0
  295. package/dist/src/runway/server/runway-mcp-server.d.ts +46 -0
  296. package/dist/src/runway/server/runway-mcp-server.d.ts.map +1 -0
  297. package/dist/src/runway/server/runway-mcp-server.js +601 -0
  298. package/dist/src/runway/server/runway-mcp-server.js.map +1 -0
  299. package/dist/src/runway.bak/auth/auth-middleware.d.ts +66 -0
  300. package/dist/src/runway.bak/auth/auth-middleware.d.ts.map +1 -0
  301. package/dist/src/runway.bak/auth/auth-middleware.js +337 -0
  302. package/dist/src/runway.bak/auth/auth-middleware.js.map +1 -0
  303. package/dist/src/runway.bak/server/runway-mcp-server.d.ts +46 -0
  304. package/dist/src/runway.bak/server/runway-mcp-server.d.ts.map +1 -0
  305. package/dist/src/runway.bak/server/runway-mcp-server.js +601 -0
  306. package/dist/src/runway.bak/server/runway-mcp-server.js.map +1 -0
  307. package/dist/src/servers/production/auth-middleware.d.ts +66 -0
  308. package/dist/src/servers/production/auth-middleware.d.ts.map +1 -0
  309. package/dist/src/servers/production/auth-middleware.js +346 -0
  310. package/dist/src/servers/production/auth-middleware.js.map +1 -0
  311. package/dist/src/servers/railway/index.d.ts +7 -0
  312. package/dist/src/servers/railway/index.d.ts.map +1 -0
  313. package/dist/src/servers/railway/index.js +401 -0
  314. package/dist/src/servers/railway/index.js.map +1 -0
  315. package/dist/src/services/config-service.d.ts +44 -0
  316. package/dist/src/services/config-service.d.ts.map +1 -0
  317. package/dist/src/services/config-service.js +61 -0
  318. package/dist/src/services/config-service.js.map +1 -0
  319. package/dist/src/services/context-service.d.ts +17 -0
  320. package/dist/src/services/context-service.d.ts.map +1 -0
  321. package/dist/src/services/context-service.js +88 -0
  322. package/dist/src/services/context-service.js.map +1 -0
  323. package/dist/src/types/task.d.ts +17 -0
  324. package/dist/src/types/task.d.ts.map +1 -0
  325. package/dist/src/types/task.js +2 -0
  326. package/dist/src/types/task.js.map +1 -0
  327. package/dist/src/utils/logger.d.ts +13 -0
  328. package/dist/src/utils/logger.d.ts.map +1 -0
  329. package/dist/src/utils/logger.js +52 -0
  330. package/dist/src/utils/logger.js.map +1 -0
  331. package/package.json +40 -5
@@ -0,0 +1,944 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * StackMemory CLI
4
+ * Command-line interface for StackMemory operations
5
+ */
6
+ import { program } from 'commander';
7
+ import { logger } from '../core/monitoring/logger.js';
8
+ import { FrameManager } from '../core/context/frame-manager.js';
9
+ import { sessionManager, FrameQueryMode } from '../core/session/index.js';
10
+ import { PebblesTaskStore } from '../features/tasks/pebbles-task-store.js';
11
+ import { LinearAuthManager, LinearOAuthSetup, } from '../integrations/linear/auth.js';
12
+ import { LinearSyncEngine, DEFAULT_SYNC_CONFIG, } from '../integrations/linear/sync.js';
13
+ import { initializeAutoSync, getAutoSyncService, stopAutoSync, } from '../integrations/linear/auto-sync.js';
14
+ import { LinearConfigManager } from '../integrations/linear/config.js';
15
+ import { UpdateChecker } from '../core/utils/update-checker.js';
16
+ import { ProgressTracker } from '../core/monitoring/progress-tracker.js';
17
+ import { registerProjectCommands } from './commands/projects.js';
18
+ import { registerLinearCommands } from './commands/linear.js';
19
+ import { registerLinearTestCommand } from './commands/linear-test.js';
20
+ import { createSessionCommands } from './commands/session.js';
21
+ import { registerWorktreeCommands } from './commands/worktree.js';
22
+ import { registerOnboardingCommand } from './commands/onboard.js';
23
+ import { webhookCommand } from './commands/webhook.js';
24
+ import { createTaskCommands } from './commands/tasks.js';
25
+ import { createSearchCommand } from './commands/search.js';
26
+ import { createLogCommand } from './commands/log.js';
27
+ import { createContextCommands } from './commands/context.js';
28
+ import { ProjectManager } from '../core/projects/project-manager.js';
29
+ import Database from 'better-sqlite3';
30
+ import { join } from 'path';
31
+ import { existsSync, mkdirSync } from 'fs';
32
+ const VERSION = '0.2.7';
33
+ // Check for updates on CLI startup
34
+ UpdateChecker.checkForUpdates(VERSION, true).catch(() => {
35
+ // Silently ignore errors
36
+ });
37
+ program
38
+ .name('stackmemory')
39
+ .description('Lossless memory runtime for AI coding tools')
40
+ .version(VERSION);
41
+ program
42
+ .command('init')
43
+ .description('Initialize StackMemory in current project')
44
+ .action(async () => {
45
+ try {
46
+ const projectRoot = process.cwd();
47
+ const dbDir = join(projectRoot, '.stackmemory');
48
+ if (!existsSync(dbDir)) {
49
+ mkdirSync(dbDir, { recursive: true });
50
+ }
51
+ const dbPath = join(dbDir, 'context.db');
52
+ const db = new Database(dbPath);
53
+ new FrameManager(db, 'cli-project');
54
+ logger.info('StackMemory initialized successfully', { projectRoot });
55
+ console.log('āœ… StackMemory initialized in', projectRoot);
56
+ db.close();
57
+ }
58
+ catch (error) {
59
+ logger.error('Failed to initialize StackMemory', error);
60
+ console.error('āŒ Initialization failed:', error.message);
61
+ process.exit(1);
62
+ }
63
+ });
64
+ program
65
+ .command('status')
66
+ .description('Show current StackMemory status')
67
+ .option('--all', 'Show all active frames across sessions')
68
+ .option('--project', 'Show all active frames in current project')
69
+ .option('--session <id>', 'Show frames for specific session')
70
+ .action(async (options) => {
71
+ try {
72
+ const projectRoot = process.cwd();
73
+ const dbPath = join(projectRoot, '.stackmemory', 'context.db');
74
+ if (!existsSync(dbPath)) {
75
+ console.log('āŒ StackMemory not initialized. Run "stackmemory init" first.');
76
+ return;
77
+ }
78
+ // Check for updates and display if available
79
+ await UpdateChecker.checkForUpdates(VERSION);
80
+ // Initialize session manager
81
+ await sessionManager.initialize();
82
+ const session = await sessionManager.getOrCreateSession({
83
+ projectPath: projectRoot,
84
+ sessionId: options.session,
85
+ });
86
+ const db = new Database(dbPath);
87
+ const frameManager = new FrameManager(db, session.projectId);
88
+ // Set query mode based on options
89
+ if (options.all) {
90
+ frameManager.setQueryMode(FrameQueryMode.ALL_ACTIVE);
91
+ }
92
+ else if (options.project) {
93
+ frameManager.setQueryMode(FrameQueryMode.PROJECT_ACTIVE);
94
+ }
95
+ const activeFrames = frameManager.getActiveFramePath();
96
+ const stackDepth = frameManager.getStackDepth();
97
+ console.log('šŸ“Š StackMemory Status:');
98
+ console.log(` Session: ${session.sessionId.slice(0, 8)} (${session.state}, ${Math.round((Date.now() - session.startedAt) / 1000 / 60)}min old)`);
99
+ console.log(` Project: ${session.projectId}`);
100
+ if (session.branch) {
101
+ console.log(` Branch: ${session.branch}`);
102
+ }
103
+ console.log(`\n Current Session:`);
104
+ console.log(` Stack depth: ${stackDepth}`);
105
+ console.log(` Active frames: ${activeFrames.length}`);
106
+ if (activeFrames.length > 0) {
107
+ activeFrames.forEach((frame, i) => {
108
+ const indent = ' ' + ' '.repeat(frame.depth || i);
109
+ const prefix = i === 0 ? '└─' : ' └─';
110
+ console.log(`${indent}${prefix} ${frame.name} [${frame.type}]`);
111
+ });
112
+ }
113
+ // Show other sessions if in default mode
114
+ if (!options.all && !options.project) {
115
+ const otherSessions = await sessionManager.listSessions({
116
+ projectId: session.projectId,
117
+ state: 'active',
118
+ });
119
+ const otherActive = otherSessions.filter((s) => s.sessionId !== session.sessionId);
120
+ if (otherActive.length > 0) {
121
+ console.log(`\n Other Active Sessions (same project):`);
122
+ otherActive.forEach((s) => {
123
+ const age = Math.round((Date.now() - s.lastActiveAt) / 1000 / 60 / 60);
124
+ console.log(` - ${s.sessionId.slice(0, 8)}: ${s.branch || 'main'}, ${age}h old`);
125
+ });
126
+ console.log(`\n Tip: Use --all to see frames across sessions`);
127
+ }
128
+ }
129
+ db.close();
130
+ }
131
+ catch (error) {
132
+ logger.error('Failed to get status', error);
133
+ console.error('āŒ Status check failed:', error.message);
134
+ process.exit(1);
135
+ }
136
+ });
137
+ // Linear Integration Commands
138
+ const linearCommand = program
139
+ .command('linear')
140
+ .description('Linear API integration commands');
141
+ linearCommand
142
+ .command('setup')
143
+ .description('Setup Linear OAuth integration')
144
+ .action(async () => {
145
+ try {
146
+ const projectRoot = process.cwd();
147
+ const linearSetup = new LinearOAuthSetup(projectRoot);
148
+ const { authUrl, instructions } = await linearSetup.setupInteractive();
149
+ console.log('šŸ”— Linear OAuth Setup\n');
150
+ instructions.forEach((instruction) => {
151
+ console.log(instruction);
152
+ });
153
+ if (authUrl) {
154
+ console.log('\nšŸ“‹ Next step: Complete authorization and run:');
155
+ console.log('stackmemory linear authorize <auth-code>');
156
+ }
157
+ }
158
+ catch (error) {
159
+ logger.error('Linear setup failed', error);
160
+ console.error('āŒ Setup failed:', error.message);
161
+ process.exit(1);
162
+ }
163
+ });
164
+ linearCommand
165
+ .command('authorize')
166
+ .description('Complete Linear OAuth authorization')
167
+ .argument('<code>', 'Authorization code from Linear')
168
+ .action(async (authCode) => {
169
+ try {
170
+ const projectRoot = process.cwd();
171
+ const linearSetup = new LinearOAuthSetup(projectRoot);
172
+ const success = await linearSetup.completeAuth(authCode);
173
+ if (success) {
174
+ console.log('āœ… Linear integration authorized successfully!');
175
+ console.log('🧪 Testing connection...');
176
+ const connectionOk = await linearSetup.testConnection();
177
+ if (connectionOk) {
178
+ console.log('āœ… Linear connection test passed!');
179
+ console.log('\nšŸš€ You can now use:');
180
+ console.log('- stackmemory linear sync');
181
+ console.log('- stackmemory linear status');
182
+ }
183
+ else {
184
+ console.log('āš ļø Linear connection test failed. Check your configuration.');
185
+ }
186
+ }
187
+ else {
188
+ console.error('āŒ Authorization failed. Please try again.');
189
+ process.exit(1);
190
+ }
191
+ }
192
+ catch (error) {
193
+ logger.error('Linear authorization failed', error);
194
+ console.error('āŒ Authorization failed:', error.message);
195
+ process.exit(1);
196
+ }
197
+ });
198
+ linearCommand
199
+ .command('status')
200
+ .description('Show Linear integration status')
201
+ .action(async () => {
202
+ try {
203
+ const projectRoot = process.cwd();
204
+ const authManager = new LinearAuthManager(projectRoot);
205
+ const isConfigured = authManager.isConfigured();
206
+ console.log('šŸ“Š Linear Integration Status:');
207
+ console.log(` Configured: ${isConfigured ? 'āœ…' : 'āŒ'}`);
208
+ if (isConfigured) {
209
+ const config = authManager.loadConfig();
210
+ const tokens = authManager.loadTokens();
211
+ console.log(` Client ID: ${config?.clientId ? config.clientId.substring(0, 8) + '...' : 'Not set'}`);
212
+ console.log(` Tokens: ${tokens ? 'āœ… Valid' : 'āŒ Missing'}`);
213
+ if (tokens) {
214
+ const expiresIn = Math.floor((tokens.expiresAt - Date.now()) / 1000 / 60);
215
+ console.log(` Token expires: ${expiresIn > 0 ? `${expiresIn} minutes` : 'Expired'}`);
216
+ }
217
+ // Test connection
218
+ console.log('\n🧪 Testing connection...');
219
+ const linearSetup = new LinearOAuthSetup(projectRoot);
220
+ const connectionOk = await linearSetup.testConnection();
221
+ console.log(` Connection: ${connectionOk ? 'āœ… OK' : 'āŒ Failed'}`);
222
+ }
223
+ else {
224
+ console.log('\nšŸ’” Run "stackmemory linear setup" to get started');
225
+ }
226
+ }
227
+ catch (error) {
228
+ logger.error('Linear status check failed', error);
229
+ console.error('āŒ Status check failed:', error.message);
230
+ process.exit(1);
231
+ }
232
+ });
233
+ linearCommand
234
+ .command('sync')
235
+ .description('Sync tasks with Linear')
236
+ .option('-d, --direction <direction>', 'Sync direction: bidirectional, to_linear, from_linear', 'bidirectional')
237
+ .action(async (options) => {
238
+ try {
239
+ const projectRoot = process.cwd();
240
+ const dbPath = join(projectRoot, '.stackmemory', 'context.db');
241
+ if (!existsSync(dbPath)) {
242
+ console.log('āŒ StackMemory not initialized. Run "stackmemory init" first.');
243
+ return;
244
+ }
245
+ const authManager = new LinearAuthManager(projectRoot);
246
+ // Check for API key from environment first
247
+ if (!process.env.LINEAR_API_KEY && !authManager.isConfigured()) {
248
+ console.log('āŒ Linear not configured. Set LINEAR_API_KEY environment variable or run "stackmemory linear setup" first.');
249
+ return;
250
+ }
251
+ const db = new Database(dbPath);
252
+ const taskStore = new PebblesTaskStore(projectRoot, db);
253
+ const syncConfig = {
254
+ ...DEFAULT_SYNC_CONFIG,
255
+ enabled: true,
256
+ direction: options.direction,
257
+ };
258
+ const linearSync = new LinearSyncEngine(taskStore, authManager, syncConfig);
259
+ console.log(`šŸ”„ Starting ${options.direction} sync with Linear...`);
260
+ const result = await linearSync.sync();
261
+ // Track progress
262
+ const progress = new ProgressTracker(projectRoot);
263
+ if (result.success) {
264
+ console.log('āœ… Sync completed successfully!');
265
+ console.log(` To Linear: ${result.synced.toLinear} created`);
266
+ console.log(` From Linear: ${result.synced.fromLinear} created`);
267
+ console.log(` Updated: ${result.synced.updated}`);
268
+ // Update progress tracker
269
+ progress.updateLinearStatus({
270
+ lastSync: new Date().toISOString(),
271
+ tasksSynced: result.synced.toLinear +
272
+ result.synced.fromLinear +
273
+ result.synced.updated,
274
+ });
275
+ if (result.conflicts.length > 0) {
276
+ console.log(`\nāš ļø Conflicts detected: ${result.conflicts.length}`);
277
+ result.conflicts.forEach((conflict) => {
278
+ console.log(` - ${conflict.taskId}: ${conflict.reason}`);
279
+ });
280
+ }
281
+ }
282
+ else {
283
+ console.log('āŒ Sync failed');
284
+ if (result.errors.length > 0) {
285
+ result.errors.forEach((error) => {
286
+ console.log(` Error: ${error}`);
287
+ });
288
+ }
289
+ }
290
+ db.close();
291
+ }
292
+ catch (error) {
293
+ logger.error('Linear sync failed', error);
294
+ console.error('āŒ Sync failed:', error.message);
295
+ process.exit(1);
296
+ }
297
+ });
298
+ // Auto-sync commands
299
+ linearCommand
300
+ .command('auto-sync')
301
+ .description('Manage automatic synchronization')
302
+ .option('--start', 'Start auto-sync service')
303
+ .option('--stop', 'Stop auto-sync service')
304
+ .option('--status', 'Show auto-sync status')
305
+ .option('--interval <minutes>', 'Set sync interval in minutes', '5')
306
+ .option('--direction <direction>', 'Set sync direction: bidirectional, to_linear, from_linear', 'bidirectional')
307
+ .option('--quiet-start <hour>', 'Start of quiet hours (0-23)', '22')
308
+ .option('--quiet-end <hour>', 'End of quiet hours (0-23)', '7')
309
+ .action(async (options) => {
310
+ try {
311
+ const projectRoot = process.cwd();
312
+ if (options.status) {
313
+ const service = getAutoSyncService();
314
+ if (service) {
315
+ const status = service.getStatus();
316
+ console.log('šŸ“Š Linear Auto-Sync Status:');
317
+ console.log(` Running: ${status.running ? 'āœ…' : 'āŒ'}`);
318
+ console.log(` Direction: ${status.config.direction}`);
319
+ console.log(` Interval: ${status.config.interval} minutes`);
320
+ console.log(` Conflict Resolution: ${status.config.conflictResolution}`);
321
+ if (status.lastSyncTime > 0) {
322
+ const lastSync = new Date(status.lastSyncTime);
323
+ console.log(` Last Sync: ${lastSync.toLocaleString()}`);
324
+ }
325
+ if (status.nextSyncTime) {
326
+ const nextSync = new Date(status.nextSyncTime);
327
+ console.log(` Next Sync: ${nextSync.toLocaleString()}`);
328
+ }
329
+ if (status.config.quietHours) {
330
+ console.log(` Quiet Hours: ${status.config.quietHours.start}:00 - ${status.config.quietHours.end}:00`);
331
+ }
332
+ if (status.retryCount > 0) {
333
+ console.log(` āš ļø Retry Count: ${status.retryCount}`);
334
+ }
335
+ }
336
+ else {
337
+ console.log('šŸ“Š Linear Auto-Sync Status: āŒ Not running');
338
+ }
339
+ return;
340
+ }
341
+ if (options.start) {
342
+ const authManager = new LinearAuthManager(projectRoot);
343
+ if (!authManager.isConfigured()) {
344
+ console.log('āŒ Linear not configured. Run "stackmemory linear setup" first.');
345
+ return;
346
+ }
347
+ const config = {
348
+ interval: parseInt(options.interval),
349
+ direction: options.direction,
350
+ quietHours: {
351
+ start: parseInt(options.quietStart),
352
+ end: parseInt(options.quietEnd),
353
+ },
354
+ };
355
+ const service = initializeAutoSync(projectRoot, config);
356
+ await service.start();
357
+ console.log('āœ… Linear auto-sync started');
358
+ console.log(` Interval: ${config.interval} minutes`);
359
+ console.log(` Direction: ${config.direction}`);
360
+ console.log(` Quiet Hours: ${config.quietHours.start}:00 - ${config.quietHours.end}:00`);
361
+ console.log('\nšŸ’” Use "stackmemory linear auto-sync --status" to check status');
362
+ // Keep process alive for auto-sync
363
+ process.on('SIGINT', () => {
364
+ console.log('\nšŸ›‘ Stopping auto-sync service...');
365
+ service.stop();
366
+ process.exit(0);
367
+ });
368
+ console.log('šŸ”„ Auto-sync running... Press Ctrl+C to stop');
369
+ // Keep the process running
370
+ await new Promise(() => { }); // Intentionally never resolves
371
+ }
372
+ if (options.stop) {
373
+ stopAutoSync();
374
+ console.log('šŸ›‘ Linear auto-sync stopped');
375
+ }
376
+ if (!options.start && !options.stop && !options.status) {
377
+ console.log('šŸ’” Usage:');
378
+ console.log(' --start Start auto-sync service');
379
+ console.log(' --stop Stop auto-sync service');
380
+ console.log(' --status Show current status');
381
+ console.log('\nExample: stackmemory linear auto-sync --start --interval 10');
382
+ }
383
+ }
384
+ catch (error) {
385
+ logger.error('Linear auto-sync command failed', error);
386
+ console.error('āŒ Auto-sync failed:', error.message);
387
+ process.exit(1);
388
+ }
389
+ });
390
+ linearCommand
391
+ .command('force-sync')
392
+ .description('Force immediate synchronization')
393
+ .action(async () => {
394
+ try {
395
+ const service = getAutoSyncService();
396
+ if (service) {
397
+ console.log('šŸ”„ Forcing immediate sync...');
398
+ await service.forceSync();
399
+ console.log('āœ… Sync completed');
400
+ }
401
+ else {
402
+ console.log('āŒ Auto-sync service not running. Use manual sync instead:');
403
+ console.log(' stackmemory linear sync');
404
+ }
405
+ }
406
+ catch (error) {
407
+ logger.error('Force sync failed', error);
408
+ console.error('āŒ Force sync failed:', error.message);
409
+ process.exit(1);
410
+ }
411
+ });
412
+ linearCommand
413
+ .command('update <issueId>')
414
+ .description('Update Linear task status')
415
+ .option('-s, --status <status>', 'New status (todo, in-progress, done, canceled)')
416
+ .option('-t, --title <title>', 'Update task title')
417
+ .option('-d, --description <desc>', 'Update task description')
418
+ .option('-p, --priority <priority>', 'Set priority (1=urgent, 2=high, 3=medium, 4=low)')
419
+ .action(async (issueId, options) => {
420
+ try {
421
+ const projectRoot = process.cwd();
422
+ const authManager = new LinearAuthManager(projectRoot);
423
+ const tokens = authManager.loadTokens();
424
+ if (!tokens) {
425
+ console.error('āŒ Not authenticated. Run: stackmemory linear setup');
426
+ process.exit(1);
427
+ }
428
+ const { LinearClient } = await import('../integrations/linear/client.js');
429
+ const client = new LinearClient({
430
+ apiKey: tokens.accessToken,
431
+ });
432
+ // Find the issue first
433
+ let issue = await client.getIssue(issueId);
434
+ if (!issue) {
435
+ // Try finding by identifier
436
+ issue = await client.findIssueByIdentifier(issueId);
437
+ }
438
+ if (!issue) {
439
+ console.error(`āŒ Issue ${issueId} not found`);
440
+ process.exit(1);
441
+ }
442
+ const updates = {};
443
+ // Handle status update
444
+ if (options.status) {
445
+ const team = await client.getTeam();
446
+ const states = await client.getWorkflowStates(team.id);
447
+ const statusMap = {
448
+ todo: 'unstarted',
449
+ 'in-progress': 'started',
450
+ done: 'completed',
451
+ canceled: 'cancelled',
452
+ };
453
+ const targetType = statusMap[options.status.toLowerCase()] || options.status;
454
+ const targetState = states.find((s) => s.type === targetType);
455
+ if (!targetState) {
456
+ console.error(`āŒ Invalid status: ${options.status}`);
457
+ console.log('Available states:');
458
+ states.forEach((s) => console.log(` - ${s.name} (${s.type})`));
459
+ process.exit(1);
460
+ }
461
+ updates.stateId = targetState.id;
462
+ }
463
+ if (options.title)
464
+ updates.title = options.title;
465
+ if (options.description)
466
+ updates.description = options.description;
467
+ if (options.priority)
468
+ updates.priority = parseInt(options.priority);
469
+ // Perform update
470
+ const updatedIssue = await client.updateIssue(issue.id, updates);
471
+ console.log(`āœ… Updated ${updatedIssue.identifier}: ${updatedIssue.title}`);
472
+ if (options.status) {
473
+ console.log(` Status: ${updatedIssue.state.name}`);
474
+ }
475
+ console.log(` ${updatedIssue.url}`);
476
+ // Auto-sync to local tasks after update
477
+ console.log('\nšŸ”„ Syncing to local tasks...');
478
+ const dbPath = join(projectRoot, '.stackmemory', 'context.db');
479
+ if (existsSync(dbPath)) {
480
+ const db = new Database(dbPath);
481
+ const taskStore = new PebblesTaskStore(projectRoot, db);
482
+ const { LinearSyncEngine, DEFAULT_SYNC_CONFIG } = await import('../integrations/linear/sync.js');
483
+ const syncEngine = new LinearSyncEngine(taskStore, authManager, { ...DEFAULT_SYNC_CONFIG, enabled: true, direction: 'from_linear' }, projectRoot);
484
+ const syncResult = await syncEngine.sync();
485
+ if (syncResult.success) {
486
+ console.log(` āœ… Local tasks synced (${syncResult.synced.fromLinear} new, ${syncResult.synced.updated} updated)`);
487
+ }
488
+ db.close();
489
+ }
490
+ }
491
+ catch (error) {
492
+ logger.error('Failed to update Linear task', error);
493
+ console.error('āŒ Failed to update task:', error.message);
494
+ process.exit(1);
495
+ }
496
+ });
497
+ linearCommand
498
+ .command('config')
499
+ .description('Configure auto-sync settings')
500
+ .option('--show', 'Show current configuration')
501
+ .option('--set-interval <minutes>', 'Set sync interval in minutes')
502
+ .option('--set-direction <direction>', 'Set sync direction: bidirectional, to_linear, from_linear')
503
+ .option('--set-conflict-resolution <strategy>', 'Set conflict resolution: newest_wins, linear_wins, stackmemory_wins, manual')
504
+ .option('--set-quiet-start <hour>', 'Set start of quiet hours (0-23)')
505
+ .option('--set-quiet-end <hour>', 'Set end of quiet hours (0-23)')
506
+ .option('--enable', 'Enable auto-sync')
507
+ .option('--disable', 'Disable auto-sync')
508
+ .option('--reset', 'Reset to default configuration')
509
+ .action(async (options) => {
510
+ try {
511
+ const projectRoot = process.cwd();
512
+ const configManager = new LinearConfigManager(projectRoot);
513
+ if (options.reset) {
514
+ configManager.resetConfig();
515
+ console.log('āœ… Configuration reset to defaults');
516
+ return;
517
+ }
518
+ if (options.show) {
519
+ const config = configManager.loadConfig();
520
+ if (config) {
521
+ console.log('šŸ“Š Linear Auto-Sync Configuration:');
522
+ console.log(` Enabled: ${config.enabled ? 'āœ…' : 'āŒ'}`);
523
+ console.log(` Interval: ${config.interval} minutes`);
524
+ console.log(` Direction: ${config.direction}`);
525
+ console.log(` Conflict Resolution: ${config.conflictResolution}`);
526
+ console.log(` Retry Attempts: ${config.retryAttempts}`);
527
+ console.log(` Retry Delay: ${config.retryDelay / 1000}s`);
528
+ if (config.quietHours) {
529
+ console.log(` Quiet Hours: ${config.quietHours.start}:00 - ${config.quietHours.end}:00`);
530
+ }
531
+ const lastUpdated = new Date(config.lastUpdated);
532
+ console.log(` Last Updated: ${lastUpdated.toLocaleString()}`);
533
+ }
534
+ else {
535
+ console.log('šŸ“Š No configuration found. Using defaults.');
536
+ const defaultConfig = configManager.getDefaultConfig();
537
+ console.log(` Default interval: ${defaultConfig.interval} minutes`);
538
+ console.log(` Default direction: ${defaultConfig.direction}`);
539
+ }
540
+ return;
541
+ }
542
+ // Update configuration
543
+ const updates = {};
544
+ if (options.setInterval) {
545
+ const interval = parseInt(options.setInterval);
546
+ if (isNaN(interval) || interval < 1) {
547
+ console.error('āŒ Interval must be a positive number');
548
+ process.exit(1);
549
+ }
550
+ updates.interval = interval;
551
+ console.log(`āœ… Set interval to ${interval} minutes`);
552
+ }
553
+ if (options.setDirection) {
554
+ const validDirections = ['bidirectional', 'to_linear', 'from_linear'];
555
+ if (!validDirections.includes(options.setDirection)) {
556
+ console.error(`āŒ Invalid direction. Must be one of: ${validDirections.join(', ')}`);
557
+ process.exit(1);
558
+ }
559
+ updates.direction = options.setDirection;
560
+ console.log(`āœ… Set direction to ${options.setDirection}`);
561
+ }
562
+ if (options.setConflictResolution) {
563
+ const validStrategies = [
564
+ 'newest_wins',
565
+ 'linear_wins',
566
+ 'stackmemory_wins',
567
+ 'manual',
568
+ ];
569
+ if (!validStrategies.includes(options.setConflictResolution)) {
570
+ console.error(`āŒ Invalid strategy. Must be one of: ${validStrategies.join(', ')}`);
571
+ process.exit(1);
572
+ }
573
+ updates.conflictResolution = options.setConflictResolution;
574
+ console.log(`āœ… Set conflict resolution to ${options.setConflictResolution}`);
575
+ }
576
+ if (options.setQuietStart) {
577
+ const hour = parseInt(options.setQuietStart);
578
+ if (isNaN(hour) || hour < 0 || hour > 23) {
579
+ console.error('āŒ Quiet start hour must be between 0 and 23');
580
+ process.exit(1);
581
+ }
582
+ const currentConfig = configManager.loadConfig() || configManager.getDefaultConfig();
583
+ updates.quietHours = {
584
+ start: hour,
585
+ end: currentConfig.quietHours?.end || 7,
586
+ };
587
+ console.log(`āœ… Set quiet hours start to ${hour}:00`);
588
+ }
589
+ if (options.setQuietEnd) {
590
+ const hour = parseInt(options.setQuietEnd);
591
+ if (isNaN(hour) || hour < 0 || hour > 23) {
592
+ console.error('āŒ Quiet end hour must be between 0 and 23');
593
+ process.exit(1);
594
+ }
595
+ const currentConfig = configManager.loadConfig() || configManager.getDefaultConfig();
596
+ updates.quietHours = {
597
+ start: currentConfig.quietHours?.start || 22,
598
+ end: hour,
599
+ };
600
+ console.log(`āœ… Set quiet hours end to ${hour}:00`);
601
+ }
602
+ if (options.enable) {
603
+ updates.enabled = true;
604
+ console.log('āœ… Auto-sync enabled');
605
+ }
606
+ if (options.disable) {
607
+ updates.enabled = false;
608
+ console.log('āŒ Auto-sync disabled');
609
+ }
610
+ if (Object.keys(updates).length > 0) {
611
+ configManager.saveConfig(updates);
612
+ console.log('\nšŸ’” Configuration updated. Restart auto-sync service to apply changes.');
613
+ }
614
+ else if (!options.show) {
615
+ console.log('šŸ’” Use --show to view current configuration');
616
+ console.log('šŸ’” Use --help to see all configuration options');
617
+ }
618
+ }
619
+ catch (error) {
620
+ logger.error('Linear config command failed', error);
621
+ console.error('āŒ Config failed:', error.message);
622
+ process.exit(1);
623
+ }
624
+ });
625
+ program
626
+ .command('update-check')
627
+ .description('Check for StackMemory updates')
628
+ .action(async () => {
629
+ try {
630
+ console.log('šŸ” Checking for updates...');
631
+ await UpdateChecker.forceCheck(VERSION);
632
+ }
633
+ catch (error) {
634
+ logger.error('Update check failed', error);
635
+ console.error('āŒ Update check failed:', error.message);
636
+ process.exit(1);
637
+ }
638
+ });
639
+ program
640
+ .command('analytics')
641
+ .description('Launch task analytics dashboard')
642
+ .option('-p, --port <port>', 'Port for dashboard server', '3000')
643
+ .option('-o, --open', 'Open dashboard in browser')
644
+ .option('--export <format>', 'Export metrics (json|csv)')
645
+ .option('--sync', 'Sync with Linear before launching')
646
+ .option('--view', 'Show analytics in terminal')
647
+ .action(async (options) => {
648
+ try {
649
+ const projectRoot = process.cwd();
650
+ const dbPath = join(projectRoot, '.stackmemory', 'context.db');
651
+ if (!existsSync(dbPath)) {
652
+ console.log('āŒ StackMemory not initialized. Run "stackmemory init" first.');
653
+ return;
654
+ }
655
+ if (options.view) {
656
+ const { displayAnalyticsDashboard } = await import('./utils/viewer.js');
657
+ await displayAnalyticsDashboard(projectRoot);
658
+ return;
659
+ }
660
+ if (options.export) {
661
+ const { AnalyticsService } = await import('../features/analytics/index.js');
662
+ const service = new AnalyticsService(projectRoot);
663
+ if (options.sync) {
664
+ console.log('šŸ”„ Syncing with Linear...');
665
+ await service.syncLinearTasks();
666
+ }
667
+ const state = await service.getDashboardState();
668
+ if (options.export === 'csv') {
669
+ console.log('šŸ“Š Exporting metrics as CSV...');
670
+ // Convert to CSV format
671
+ const tasks = state.recentTasks;
672
+ const headers = [
673
+ 'ID',
674
+ 'Title',
675
+ 'State',
676
+ 'Priority',
677
+ 'Created',
678
+ 'Completed',
679
+ ];
680
+ const rows = tasks.map((t) => [
681
+ t.id,
682
+ t.title,
683
+ t.state,
684
+ t.priority,
685
+ t.createdAt.toISOString(),
686
+ t.completedAt?.toISOString() || '',
687
+ ]);
688
+ console.log(headers.join(','));
689
+ rows.forEach((r) => console.log(r.join(',')));
690
+ }
691
+ else {
692
+ console.log(JSON.stringify(state, null, 2));
693
+ }
694
+ service.close();
695
+ return;
696
+ }
697
+ // Launch dashboard server
698
+ console.log(`šŸš€ Launching analytics dashboard on port ${options.port}...`);
699
+ const express = (await import('express')).default;
700
+ const { AnalyticsAPI } = await import('../features/analytics/index.js');
701
+ const { createServer } = await import('http');
702
+ const app = express();
703
+ // Add error handling middleware
704
+ app.use((err, req, res, _next) => {
705
+ console.error('Express error:', err);
706
+ res.status(500).json({ error: err.message });
707
+ });
708
+ const analyticsAPI = new AnalyticsAPI(projectRoot);
709
+ if (options.sync) {
710
+ console.log('šŸ”„ Syncing with Linear...');
711
+ const service = new (await import('../features/analytics/index.js')).AnalyticsService(projectRoot);
712
+ await service.syncLinearTasks();
713
+ service.close();
714
+ }
715
+ app.use('/api/analytics', analyticsAPI.getRouter());
716
+ // Serve the HTML dashboard
717
+ app.get('/', async (req, res) => {
718
+ // Try multiple paths for the dashboard HTML
719
+ const possiblePaths = [
720
+ join(projectRoot, 'src/features/analytics/dashboard.html'),
721
+ join(projectRoot, 'dist/features/analytics/dashboard.html'),
722
+ ];
723
+ for (const dashboardPath of possiblePaths) {
724
+ if (existsSync(dashboardPath)) {
725
+ res.sendFile(dashboardPath);
726
+ return;
727
+ }
728
+ }
729
+ // Inline fallback dashboard
730
+ res.send(`<!DOCTYPE html>
731
+ <html lang="en">
732
+ <head>
733
+ <meta charset="UTF-8">
734
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
735
+ <title>StackMemory Analytics</title>
736
+ <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
737
+ <style>
738
+ * { margin: 0; padding: 0; box-sizing: border-box; }
739
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #1a1a2e; color: #eee; padding: 20px; }
740
+ .container { max-width: 1200px; margin: 0 auto; }
741
+ h1 { color: #667eea; margin-bottom: 20px; }
742
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 30px; }
743
+ .card { background: #16213e; border-radius: 12px; padding: 20px; }
744
+ .metric-value { font-size: 2.5em; font-weight: bold; color: #667eea; }
745
+ .metric-label { color: #888; text-transform: uppercase; font-size: 0.8em; }
746
+ .task-list { max-height: 400px; overflow-y: auto; }
747
+ .task-item { padding: 10px; border-left: 3px solid #667eea; margin-bottom: 8px; background: #1a1a2e; }
748
+ .task-item.completed { border-color: #22c55e; }
749
+ .task-item.in_progress { border-color: #f59e0b; }
750
+ .status { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 0.8em; margin-right: 8px; }
751
+ .status.completed { background: #22c55e30; color: #22c55e; }
752
+ .status.in_progress { background: #f59e0b30; color: #f59e0b; }
753
+ .status.todo { background: #667eea30; color: #667eea; }
754
+ </style>
755
+ </head>
756
+ <body>
757
+ <div class="container">
758
+ <h1>šŸ“Š StackMemory Analytics</h1>
759
+ <div class="grid" id="metrics"></div>
760
+ <div class="card"><h3>Recent Tasks</h3><div class="task-list" id="tasks">Loading...</div></div>
761
+ </div>
762
+ <script>
763
+ async function load() {
764
+ const metrics = await fetch('/api/analytics/metrics').then(r => r.json());
765
+ const tasks = await fetch('/api/analytics/tasks').then(r => r.json());
766
+
767
+ document.getElementById('metrics').innerHTML = \`
768
+ <div class="card"><div class="metric-label">Total</div><div class="metric-value">\${metrics.data.metrics.totalTasks}</div></div>
769
+ <div class="card"><div class="metric-label">Completed</div><div class="metric-value">\${metrics.data.metrics.completedTasks}</div></div>
770
+ <div class="card"><div class="metric-label">In Progress</div><div class="metric-value">\${metrics.data.metrics.inProgressTasks}</div></div>
771
+ <div class="card"><div class="metric-label">Completion</div><div class="metric-value">\${metrics.data.metrics.completionRate.toFixed(0)}%</div></div>
772
+ \`;
773
+
774
+ document.getElementById('tasks').innerHTML = tasks.data.tasks.slice(0, 10).map(t => \`
775
+ <div class="task-item \${t.state}">
776
+ <span class="status \${t.state}">\${t.state}</span>
777
+ <strong>\${t.title}</strong>
778
+ </div>
779
+ \`).join('');
780
+ }
781
+ load();
782
+ setInterval(load, 30000);
783
+ </script>
784
+ </body>
785
+ </html>`);
786
+ });
787
+ const server = createServer(app);
788
+ analyticsAPI.setupWebSocket(server);
789
+ server.listen(options.port, async () => {
790
+ console.log(`āœ… Analytics dashboard running at http://localhost:${options.port}`);
791
+ if (options.open) {
792
+ const { exec } = await import('child_process');
793
+ const url = `http://localhost:${options.port}`;
794
+ const command = process.platform === 'darwin'
795
+ ? `open ${url}`
796
+ : process.platform === 'win32'
797
+ ? `start ${url}`
798
+ : `xdg-open ${url}`;
799
+ exec(command);
800
+ }
801
+ });
802
+ process.on('SIGINT', () => {
803
+ console.log('\nšŸ‘‹ Shutting down analytics dashboard...');
804
+ analyticsAPI.close();
805
+ server.close();
806
+ process.exit(0);
807
+ });
808
+ // Keep the process alive
809
+ await new Promise(() => { });
810
+ }
811
+ catch (error) {
812
+ logger.error('Analytics command failed', error);
813
+ console.error('āŒ Analytics failed:', error.message);
814
+ process.exit(1);
815
+ }
816
+ });
817
+ program
818
+ .command('progress')
819
+ .description('Show current progress and recent changes')
820
+ .action(async () => {
821
+ try {
822
+ const projectRoot = process.cwd();
823
+ const dbPath = join(projectRoot, '.stackmemory', 'context.db');
824
+ if (!existsSync(dbPath)) {
825
+ console.log('āŒ StackMemory not initialized. Run "stackmemory init" first.');
826
+ return;
827
+ }
828
+ const progress = new ProgressTracker(projectRoot);
829
+ console.log(progress.getSummary());
830
+ }
831
+ catch (error) {
832
+ logger.error('Failed to show progress', error);
833
+ console.error('āŒ Failed to show progress:', error.message);
834
+ process.exit(1);
835
+ }
836
+ });
837
+ program
838
+ .command('mcp-server')
839
+ .description('Start StackMemory MCP server for Claude Desktop')
840
+ .option('-p, --project <path>', 'Project root directory', process.cwd())
841
+ .action(async (options) => {
842
+ try {
843
+ const { runMCPServer } = await import('../integrations/mcp/server.js');
844
+ // Set project root
845
+ process.env.PROJECT_ROOT = options.project;
846
+ console.log('šŸš€ Starting StackMemory MCP Server...');
847
+ console.log(` Project: ${options.project}`);
848
+ console.log(` Version: ${VERSION}`);
849
+ // Check for updates silently
850
+ UpdateChecker.checkForUpdates(VERSION, true).catch(() => { });
851
+ // Start the MCP server
852
+ await runMCPServer();
853
+ }
854
+ catch (error) {
855
+ logger.error('Failed to start MCP server', error);
856
+ console.error('āŒ MCP server failed:', error.message);
857
+ process.exit(1);
858
+ }
859
+ });
860
+ // Add test context command
861
+ program
862
+ .command('context:test')
863
+ .description('Test context persistence by creating sample frames')
864
+ .action(async () => {
865
+ try {
866
+ const projectRoot = process.cwd();
867
+ const dbPath = join(projectRoot, '.stackmemory', 'context.db');
868
+ if (!existsSync(dbPath)) {
869
+ console.log('āŒ StackMemory not initialized. Run "stackmemory init" first.');
870
+ return;
871
+ }
872
+ const db = new Database(dbPath);
873
+ const frameManager = new FrameManager(db, 'cli-project');
874
+ // Create test frames
875
+ console.log('šŸ“ Creating test context frames...');
876
+ const rootFrame = frameManager.createFrame({
877
+ type: 'task',
878
+ name: 'Test Session',
879
+ inputs: { test: true, timestamp: new Date().toISOString() },
880
+ });
881
+ const taskFrame = frameManager.createFrame({
882
+ type: 'subtask',
883
+ name: 'Sample Task',
884
+ inputs: { description: 'Testing context persistence' },
885
+ parentFrameId: rootFrame,
886
+ });
887
+ const commandFrame = frameManager.createFrame({
888
+ type: 'tool_scope',
889
+ name: 'test-command',
890
+ inputs: { args: ['--test'] },
891
+ parentFrameId: taskFrame,
892
+ });
893
+ // Add some events
894
+ frameManager.addEvent('observation', {
895
+ message: 'Test event recorded',
896
+ }, commandFrame);
897
+ console.log('āœ… Test frames created!');
898
+ console.log(`šŸ“Š Stack depth: ${frameManager.getStackDepth()}`);
899
+ console.log(`šŸ”„ Active frames: ${frameManager.getActiveFramePath().length}`);
900
+ // Close one frame to test state changes
901
+ frameManager.closeFrame(commandFrame);
902
+ console.log(`šŸ“Š After closing command frame: depth = ${frameManager.getStackDepth()}`);
903
+ db.close();
904
+ }
905
+ catch (error) {
906
+ logger.error('Test context failed', error);
907
+ console.error('āŒ Test failed:', error.message);
908
+ process.exit(1);
909
+ }
910
+ });
911
+ // Register project management commands
912
+ // Register command modules
913
+ registerOnboardingCommand(program);
914
+ registerProjectCommands(program);
915
+ registerWorktreeCommands(program);
916
+ // Register Linear integration commands
917
+ registerLinearCommands(program);
918
+ registerLinearTestCommand(program);
919
+ // Register session management commands
920
+ program.addCommand(createSessionCommands());
921
+ // Register webhook command
922
+ program.addCommand(webhookCommand());
923
+ // Register enhanced CLI commands
924
+ program.addCommand(createTaskCommands());
925
+ program.addCommand(createSearchCommand());
926
+ program.addCommand(createLogCommand());
927
+ program.addCommand(createContextCommands());
928
+ // Auto-detect current project on startup
929
+ if (process.argv.length > 2) {
930
+ const manager = ProjectManager.getInstance();
931
+ manager.detectProject().catch(() => {
932
+ // Silently fail if not in a project directory
933
+ });
934
+ }
935
+ // Only parse when running as main module (not when imported for testing)
936
+ const isMainModule = import.meta.url === `file://${process.argv[1]}` ||
937
+ process.argv[1]?.endsWith('/stackmemory') ||
938
+ process.argv[1]?.endsWith('index.ts') ||
939
+ process.argv[1]?.includes('tsx');
940
+ if (isMainModule) {
941
+ program.parse();
942
+ }
943
+ export { program };
944
+ //# sourceMappingURL=index.js.map