@stackmemoryai/stackmemory 0.5.31 → 0.5.34

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 (148) hide show
  1. package/dist/agents/core/agent-task-manager.js.map +1 -1
  2. package/dist/cli/claude-sm.js +199 -16
  3. package/dist/cli/claude-sm.js.map +2 -2
  4. package/dist/cli/commands/clear.js +1 -1
  5. package/dist/cli/commands/clear.js.map +1 -1
  6. package/dist/cli/commands/context.js +1 -12
  7. package/dist/cli/commands/context.js.map +2 -2
  8. package/dist/cli/commands/dashboard.js.map +1 -1
  9. package/dist/cli/commands/discovery.js +1 -1
  10. package/dist/cli/commands/discovery.js.map +1 -1
  11. package/dist/cli/commands/handoff.js +1 -1
  12. package/dist/cli/commands/handoff.js.map +1 -1
  13. package/dist/cli/commands/linear.js +1 -14
  14. package/dist/cli/commands/linear.js.map +2 -2
  15. package/dist/cli/commands/login.js +32 -10
  16. package/dist/cli/commands/login.js.map +2 -2
  17. package/dist/cli/commands/migrate.js +80 -22
  18. package/dist/cli/commands/migrate.js.map +2 -2
  19. package/dist/cli/commands/model.js +533 -0
  20. package/dist/cli/commands/model.js.map +7 -0
  21. package/dist/cli/commands/monitor.js +1 -1
  22. package/dist/cli/commands/monitor.js.map +1 -1
  23. package/dist/cli/commands/quality.js +1 -1
  24. package/dist/cli/commands/quality.js.map +1 -1
  25. package/dist/cli/commands/ralph.js +93 -28
  26. package/dist/cli/commands/ralph.js.map +2 -2
  27. package/dist/cli/commands/service.js +10 -3
  28. package/dist/cli/commands/service.js.map +2 -2
  29. package/dist/cli/commands/skills.js +61 -11
  30. package/dist/cli/commands/skills.js.map +2 -2
  31. package/dist/cli/commands/sms-notify.js +342 -22
  32. package/dist/cli/commands/sms-notify.js.map +3 -3
  33. package/dist/cli/commands/workflow.js +1 -1
  34. package/dist/cli/commands/workflow.js.map +1 -1
  35. package/dist/cli/commands/worktree.js +1 -1
  36. package/dist/cli/commands/worktree.js.map +1 -1
  37. package/dist/cli/index.js +3 -1
  38. package/dist/cli/index.js.map +2 -2
  39. package/dist/core/context/auto-context.js.map +1 -1
  40. package/dist/core/context/compaction-handler.js.map +2 -2
  41. package/dist/core/context/context-bridge.js.map +2 -2
  42. package/dist/core/context/dual-stack-manager.js +24 -8
  43. package/dist/core/context/dual-stack-manager.js.map +2 -2
  44. package/dist/core/context/enhanced-rehydration.js.map +1 -1
  45. package/dist/core/context/frame-database.js +41 -5
  46. package/dist/core/context/frame-database.js.map +2 -2
  47. package/dist/core/context/frame-digest.js +6 -1
  48. package/dist/core/context/frame-digest.js.map +2 -2
  49. package/dist/core/context/frame-handoff-manager.js.map +1 -1
  50. package/dist/core/context/frame-lifecycle-hooks.js +119 -0
  51. package/dist/core/context/frame-lifecycle-hooks.js.map +7 -0
  52. package/dist/core/context/frame-manager.js +56 -9
  53. package/dist/core/context/frame-manager.js.map +2 -2
  54. package/dist/core/context/frame-stack.js +29 -0
  55. package/dist/core/context/frame-stack.js.map +2 -2
  56. package/dist/core/context/incremental-gc.js.map +2 -2
  57. package/dist/core/context/index.js +4 -22
  58. package/dist/core/context/index.js.map +2 -2
  59. package/dist/core/context/permission-manager.js +0 -11
  60. package/dist/core/context/permission-manager.js.map +2 -2
  61. package/dist/core/context/recursive-context-manager.js +15 -9
  62. package/dist/core/context/recursive-context-manager.js.map +2 -2
  63. package/dist/core/context/refactored-frame-manager.js +140 -34
  64. package/dist/core/context/refactored-frame-manager.js.map +3 -3
  65. package/dist/core/context/shared-context-layer.js +0 -11
  66. package/dist/core/context/shared-context-layer.js.map +2 -2
  67. package/dist/core/context/stack-merge-resolver.js.map +1 -1
  68. package/dist/core/context/validation.js +6 -1
  69. package/dist/core/context/validation.js.map +2 -2
  70. package/dist/core/database/database-adapter.js.map +1 -1
  71. package/dist/core/database/paradedb-adapter.js.map +1 -1
  72. package/dist/core/database/query-router.js.map +1 -1
  73. package/dist/core/database/sqlite-adapter.js.map +1 -1
  74. package/dist/core/digest/frame-digest-integration.js.map +1 -1
  75. package/dist/core/digest/hybrid-digest-generator.js.map +1 -1
  76. package/dist/core/digest/types.js.map +1 -1
  77. package/dist/core/errors/index.js +249 -0
  78. package/dist/core/errors/index.js.map +2 -2
  79. package/dist/core/frame/workflow-templates.js.map +2 -2
  80. package/dist/core/merge/conflict-detector.js.map +1 -1
  81. package/dist/core/merge/resolution-engine.js.map +1 -1
  82. package/dist/core/merge/stack-diff.js.map +1 -1
  83. package/dist/core/models/fallback-monitor.js +229 -0
  84. package/dist/core/models/fallback-monitor.js.map +7 -0
  85. package/dist/core/models/model-router.js +340 -0
  86. package/dist/core/models/model-router.js.map +7 -0
  87. package/dist/core/monitoring/error-handler.js +37 -270
  88. package/dist/core/monitoring/error-handler.js.map +3 -3
  89. package/dist/core/monitoring/session-monitor.js.map +1 -1
  90. package/dist/core/performance/lazy-context-loader.js.map +1 -1
  91. package/dist/core/performance/optimized-frame-context.js.map +1 -1
  92. package/dist/core/retrieval/context-retriever.js.map +1 -1
  93. package/dist/core/retrieval/graph-retrieval.js.map +1 -1
  94. package/dist/core/retrieval/hierarchical-retrieval.js.map +1 -1
  95. package/dist/core/retrieval/llm-context-retrieval.js.map +1 -1
  96. package/dist/core/retrieval/retrieval-benchmarks.js.map +1 -1
  97. package/dist/core/retrieval/summary-generator.js.map +1 -1
  98. package/dist/core/retrieval/types.js.map +1 -1
  99. package/dist/core/storage/chromadb-adapter.js.map +1 -1
  100. package/dist/core/storage/infinite-storage.js.map +1 -1
  101. package/dist/core/storage/two-tier-storage.js.map +1 -1
  102. package/dist/features/tasks/task-aware-context.js.map +1 -1
  103. package/dist/features/web/server/index.js +1 -1
  104. package/dist/features/web/server/index.js.map +1 -1
  105. package/dist/hooks/claude-code-whatsapp-hook.js +197 -0
  106. package/dist/hooks/claude-code-whatsapp-hook.js.map +7 -0
  107. package/dist/hooks/linear-task-picker.js +1 -1
  108. package/dist/hooks/linear-task-picker.js.map +2 -2
  109. package/dist/hooks/schemas.js +105 -1
  110. package/dist/hooks/schemas.js.map +2 -2
  111. package/dist/hooks/session-summary.js +5 -1
  112. package/dist/hooks/session-summary.js.map +2 -2
  113. package/dist/hooks/sms-action-runner.js +16 -1
  114. package/dist/hooks/sms-action-runner.js.map +2 -2
  115. package/dist/hooks/sms-notify.js +4 -2
  116. package/dist/hooks/sms-notify.js.map +2 -2
  117. package/dist/hooks/sms-webhook.js +23 -2
  118. package/dist/hooks/sms-webhook.js.map +2 -2
  119. package/dist/hooks/whatsapp-commands.js +516 -0
  120. package/dist/hooks/whatsapp-commands.js.map +7 -0
  121. package/dist/hooks/whatsapp-scheduler.js +317 -0
  122. package/dist/hooks/whatsapp-scheduler.js.map +7 -0
  123. package/dist/hooks/whatsapp-sync.js +409 -0
  124. package/dist/hooks/whatsapp-sync.js.map +7 -0
  125. package/dist/index.js +1 -1
  126. package/dist/index.js.map +1 -1
  127. package/dist/integrations/mcp/handlers/context-handlers.js.map +1 -1
  128. package/dist/integrations/mcp/handlers/discovery-handlers.js.map +1 -1
  129. package/dist/integrations/mcp/server.js +1 -1
  130. package/dist/integrations/mcp/server.js.map +1 -1
  131. package/dist/integrations/ralph/bridge/ralph-stackmemory-bridge.js +1 -1
  132. package/dist/integrations/ralph/bridge/ralph-stackmemory-bridge.js.map +1 -1
  133. package/dist/integrations/ralph/context/stackmemory-context-loader.js +1 -1
  134. package/dist/integrations/ralph/context/stackmemory-context-loader.js.map +1 -1
  135. package/dist/integrations/ralph/learning/pattern-learner.js +1 -1
  136. package/dist/integrations/ralph/learning/pattern-learner.js.map +1 -1
  137. package/dist/integrations/ralph/orchestration/multi-loop-orchestrator.js +1 -1
  138. package/dist/integrations/ralph/orchestration/multi-loop-orchestrator.js.map +1 -1
  139. package/dist/integrations/ralph/swarm/swarm-coordinator.js +1 -1
  140. package/dist/integrations/ralph/swarm/swarm-coordinator.js.map +1 -1
  141. package/dist/integrations/ralph/visualization/ralph-debugger.js +1 -1
  142. package/dist/integrations/ralph/visualization/ralph-debugger.js.map +1 -1
  143. package/dist/mcp/stackmemory-mcp-server.js +1 -1
  144. package/dist/mcp/stackmemory-mcp-server.js.map +1 -1
  145. package/dist/skills/claude-skills.js.map +1 -1
  146. package/dist/skills/recursive-agent-orchestrator.js.map +1 -1
  147. package/dist/skills/unified-rlm-orchestrator.js.map +1 -1
  148. package/package.json +2 -3
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/cli/commands/discovery.ts"],
4
- "sourcesContent": ["/**\n * Discovery CLI Commands\n * Discover relevant files based on current context\n */\n\nimport { Command } from 'commander';\nimport Database from 'better-sqlite3';\nimport { join } from 'path';\nimport { existsSync } from 'fs';\nimport chalk from 'chalk';\nimport { FrameManager } from '../../core/context/frame-manager.js';\nimport { LLMContextRetrieval } from '../../core/retrieval/index.js';\nimport { DiscoveryHandlers } from '../../integrations/mcp/handlers/discovery-handlers.js';\n\nexport function createDiscoveryCommands(): Command {\n const discovery = new Command('discovery')\n .alias('discover')\n .description('Discover relevant files based on current context');\n\n // Main discovery command\n discovery\n .command('files')\n .alias('f')\n .description('Discover files relevant to current context')\n .option('-q, --query <text>', 'Focus discovery on specific query')\n .option(\n '-d, --depth <level>',\n 'Search depth: shallow, medium, deep',\n 'medium'\n )\n .option('-m, --max <n>', 'Maximum files to return', '20')\n .option('-i, --include <patterns>', 'Include patterns (comma-separated)')\n .option('-e, --exclude <patterns>', 'Exclude patterns (comma-separated)')\n .action(async (options) => {\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n if (!existsSync(dbPath)) {\n console.log(\n chalk.red('StackMemory not initialized in this directory.')\n );\n console.log(chalk.gray('Run \"stackmemory init\" first.'));\n return;\n }\n\n const db = new Database(dbPath);\n\n try {\n let projectId = 'default';\n try {\n const row = db\n .prepare(`SELECT value FROM metadata WHERE key = 'project_id'`)\n .get() as any;\n if (row?.value) projectId = row.value;\n } catch {}\n\n const frameManager = new FrameManager(db, projectId, {\n skipContextBridge: true,\n });\n const contextRetrieval = new LLMContextRetrieval(\n db,\n frameManager,\n projectId\n );\n const handlers = new DiscoveryHandlers({\n frameManager,\n contextRetrieval,\n db,\n projectRoot,\n });\n\n console.log(chalk.blue('\\nDiscovering relevant files...\\n'));\n\n const result = await handlers.handleDiscover({\n query: options.query,\n depth: options.depth as 'shallow' | 'medium' | 'deep',\n maxFiles: parseInt(options.max),\n includePatterns: options.include?.split(','),\n excludePatterns: options.exclude?.split(','),\n });\n\n // Display results\n const metadata = result.metadata;\n\n console.log(chalk.cyan('Context Summary'));\n console.log(chalk.gray(metadata.contextSummary));\n console.log('');\n\n console.log(chalk.cyan('Keywords Extracted'));\n console.log(chalk.gray(metadata.keywords.slice(0, 15).join(', ')));\n console.log('');\n\n console.log(chalk.cyan('Relevant Files'));\n for (const file of metadata.files.slice(0, parseInt(options.max))) {\n const icon =\n file.relevance === 'high'\n ? chalk.green('[HIGH]')\n : file.relevance === 'medium'\n ? chalk.yellow('[MED]')\n : chalk.gray('[LOW]');\n console.log(`${icon} ${chalk.white(file.path)}`);\n console.log(chalk.gray(` ${file.reason}`));\n }\n\n if (Object.keys(metadata.mdContext).length > 0) {\n console.log('');\n console.log(chalk.cyan('MD Files Parsed'));\n for (const mdFile of Object.keys(metadata.mdContext)) {\n console.log(chalk.gray(` - ${mdFile}`));\n }\n }\n\n console.log('');\n } finally {\n db.close();\n }\n });\n\n // Related files command\n discovery\n .command('related')\n .alias('r')\n .description('Find files related to a specific file or concept')\n .option('-f, --file <path>', 'File to find related files for')\n .option('-c, --concept <text>', 'Concept to search for')\n .option('-m, --max <n>', 'Maximum files to return', '10')\n .action(async (options) => {\n if (!options.file && !options.concept) {\n console.log(chalk.red('Either --file or --concept is required'));\n return;\n }\n\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n if (!existsSync(dbPath)) {\n console.log(\n chalk.red('StackMemory not initialized in this directory.')\n );\n return;\n }\n\n const db = new Database(dbPath);\n\n try {\n let projectId = 'default';\n try {\n const row = db\n .prepare(`SELECT value FROM metadata WHERE key = 'project_id'`)\n .get() as any;\n if (row?.value) projectId = row.value;\n } catch {}\n\n const frameManager = new FrameManager(db, projectId, {\n skipContextBridge: true,\n });\n const contextRetrieval = new LLMContextRetrieval(\n db,\n frameManager,\n projectId\n );\n const handlers = new DiscoveryHandlers({\n frameManager,\n contextRetrieval,\n db,\n projectRoot,\n });\n\n const target = options.file || options.concept;\n console.log(chalk.blue(`\\nFinding files related to: ${target}\\n`));\n\n const result = await handlers.handleRelatedFiles({\n file: options.file,\n concept: options.concept,\n maxFiles: parseInt(options.max),\n });\n\n const files = result.metadata.relatedFiles;\n\n if (files.length === 0) {\n console.log(chalk.gray('No related files found.'));\n return;\n }\n\n for (const file of files) {\n const icon =\n file.relevance === 'high'\n ? chalk.green('[HIGH]')\n : chalk.yellow('[MED]');\n console.log(`${icon} ${chalk.white(file.path)}`);\n console.log(chalk.gray(` ${file.reason}`));\n }\n\n console.log('');\n } finally {\n db.close();\n }\n });\n\n // Session summary command\n discovery\n .command('session')\n .alias('s')\n .description('Get current session summary')\n .option('--no-files', 'Exclude recent files')\n .option('--no-decisions', 'Exclude recent decisions')\n .action(async (options) => {\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n if (!existsSync(dbPath)) {\n console.log(\n chalk.red('StackMemory not initialized in this directory.')\n );\n return;\n }\n\n const db = new Database(dbPath);\n\n try {\n let projectId = 'default';\n try {\n const row = db\n .prepare(`SELECT value FROM metadata WHERE key = 'project_id'`)\n .get() as any;\n if (row?.value) projectId = row.value;\n } catch {}\n\n const frameManager = new FrameManager(db, projectId, {\n skipContextBridge: true,\n });\n const contextRetrieval = new LLMContextRetrieval(\n db,\n frameManager,\n projectId\n );\n const handlers = new DiscoveryHandlers({\n frameManager,\n contextRetrieval,\n db,\n projectRoot,\n });\n\n const result = await handlers.handleSessionSummary({\n includeFiles: options.files !== false,\n includeDecisions: options.decisions !== false,\n });\n\n const summary = result.metadata;\n\n console.log(chalk.blue('\\nSession Summary\\n'));\n\n console.log(`${chalk.cyan('Current Goal:')} ${summary.currentGoal}`);\n console.log(`${chalk.cyan('Active Frames:')} ${summary.activeFrames}`);\n console.log(`${chalk.cyan('Stack Depth:')} ${summary.stackDepth}`);\n\n if (summary.recentFiles?.length > 0) {\n console.log(chalk.cyan('\\nRecent Files:'));\n for (const f of summary.recentFiles.slice(0, 10)) {\n console.log(chalk.gray(` - ${f}`));\n }\n }\n\n if (summary.decisions?.length > 0) {\n console.log(chalk.cyan('\\nRecent Decisions:'));\n for (const d of summary.decisions.slice(0, 5)) {\n console.log(\n chalk.gray(\n ` [${d.type}] ${d.text.slice(0, 60)}${d.text.length > 60 ? '...' : ''}`\n )\n );\n }\n }\n\n console.log('');\n } finally {\n db.close();\n }\n });\n\n // Quick context command (default)\n discovery\n .command('quick', { isDefault: true })\n .description('Quick discovery based on current context')\n .action(async () => {\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n if (!existsSync(dbPath)) {\n console.log(\n chalk.red('StackMemory not initialized in this directory.')\n );\n console.log(chalk.gray('Run \"stackmemory init\" first.'));\n return;\n }\n\n const db = new Database(dbPath);\n\n try {\n let projectId = 'default';\n try {\n const row = db\n .prepare(`SELECT value FROM metadata WHERE key = 'project_id'`)\n .get() as any;\n if (row?.value) projectId = row.value;\n } catch {}\n\n const frameManager = new FrameManager(db, projectId, {\n skipContextBridge: true,\n });\n const contextRetrieval = new LLMContextRetrieval(\n db,\n frameManager,\n projectId\n );\n const handlers = new DiscoveryHandlers({\n frameManager,\n contextRetrieval,\n db,\n projectRoot,\n });\n\n console.log(chalk.blue('\\nQuick Discovery\\n'));\n\n // Get session summary first\n const sessionResult = await handlers.handleSessionSummary({\n includeFiles: true,\n includeDecisions: true,\n });\n const session = sessionResult.metadata;\n\n console.log(`${chalk.cyan('Current:')} ${session.currentGoal}`);\n console.log(`${chalk.cyan('Stack:')} ${session.stackDepth} frames`);\n console.log('');\n\n // Quick file discovery\n const discoverResult = await handlers.handleDiscover({\n depth: 'shallow',\n maxFiles: 10,\n });\n const discovery = discoverResult.metadata;\n\n console.log(\n chalk.cyan('Keywords: ') +\n chalk.gray(discovery.keywords.slice(0, 8).join(', '))\n );\n console.log('');\n\n console.log(chalk.cyan('Top Relevant Files:'));\n for (const file of discovery.files.slice(0, 5)) {\n const icon =\n file.relevance === 'high' ? chalk.green('*') : chalk.yellow('-');\n console.log(`${icon} ${file.path}`);\n }\n\n if (session.decisions?.length > 0) {\n console.log('');\n console.log(chalk.cyan('Recent Decisions:'));\n for (const d of session.decisions.slice(0, 3)) {\n console.log(chalk.gray(` [${d.type}] ${d.text.slice(0, 50)}...`));\n }\n }\n\n console.log('');\n console.log(\n chalk.gray('Use \"stackmemory discovery files\" for detailed discovery')\n );\n } finally {\n db.close();\n }\n });\n\n return discovery;\n}\n"],
4
+ "sourcesContent": ["/**\n * Discovery CLI Commands\n * Discover relevant files based on current context\n */\n\nimport { Command } from 'commander';\nimport Database from 'better-sqlite3';\nimport { join } from 'path';\nimport { existsSync } from 'fs';\nimport chalk from 'chalk';\nimport { FrameManager } from '../../core/context/index.js';\nimport { LLMContextRetrieval } from '../../core/retrieval/index.js';\nimport { DiscoveryHandlers } from '../../integrations/mcp/handlers/discovery-handlers.js';\n\nexport function createDiscoveryCommands(): Command {\n const discovery = new Command('discovery')\n .alias('discover')\n .description('Discover relevant files based on current context');\n\n // Main discovery command\n discovery\n .command('files')\n .alias('f')\n .description('Discover files relevant to current context')\n .option('-q, --query <text>', 'Focus discovery on specific query')\n .option(\n '-d, --depth <level>',\n 'Search depth: shallow, medium, deep',\n 'medium'\n )\n .option('-m, --max <n>', 'Maximum files to return', '20')\n .option('-i, --include <patterns>', 'Include patterns (comma-separated)')\n .option('-e, --exclude <patterns>', 'Exclude patterns (comma-separated)')\n .action(async (options) => {\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n if (!existsSync(dbPath)) {\n console.log(\n chalk.red('StackMemory not initialized in this directory.')\n );\n console.log(chalk.gray('Run \"stackmemory init\" first.'));\n return;\n }\n\n const db = new Database(dbPath);\n\n try {\n let projectId = 'default';\n try {\n const row = db\n .prepare(`SELECT value FROM metadata WHERE key = 'project_id'`)\n .get() as any;\n if (row?.value) projectId = row.value;\n } catch {}\n\n const frameManager = new FrameManager(db, projectId, {\n skipContextBridge: true,\n });\n const contextRetrieval = new LLMContextRetrieval(\n db,\n frameManager,\n projectId\n );\n const handlers = new DiscoveryHandlers({\n frameManager,\n contextRetrieval,\n db,\n projectRoot,\n });\n\n console.log(chalk.blue('\\nDiscovering relevant files...\\n'));\n\n const result = await handlers.handleDiscover({\n query: options.query,\n depth: options.depth as 'shallow' | 'medium' | 'deep',\n maxFiles: parseInt(options.max),\n includePatterns: options.include?.split(','),\n excludePatterns: options.exclude?.split(','),\n });\n\n // Display results\n const metadata = result.metadata;\n\n console.log(chalk.cyan('Context Summary'));\n console.log(chalk.gray(metadata.contextSummary));\n console.log('');\n\n console.log(chalk.cyan('Keywords Extracted'));\n console.log(chalk.gray(metadata.keywords.slice(0, 15).join(', ')));\n console.log('');\n\n console.log(chalk.cyan('Relevant Files'));\n for (const file of metadata.files.slice(0, parseInt(options.max))) {\n const icon =\n file.relevance === 'high'\n ? chalk.green('[HIGH]')\n : file.relevance === 'medium'\n ? chalk.yellow('[MED]')\n : chalk.gray('[LOW]');\n console.log(`${icon} ${chalk.white(file.path)}`);\n console.log(chalk.gray(` ${file.reason}`));\n }\n\n if (Object.keys(metadata.mdContext).length > 0) {\n console.log('');\n console.log(chalk.cyan('MD Files Parsed'));\n for (const mdFile of Object.keys(metadata.mdContext)) {\n console.log(chalk.gray(` - ${mdFile}`));\n }\n }\n\n console.log('');\n } finally {\n db.close();\n }\n });\n\n // Related files command\n discovery\n .command('related')\n .alias('r')\n .description('Find files related to a specific file or concept')\n .option('-f, --file <path>', 'File to find related files for')\n .option('-c, --concept <text>', 'Concept to search for')\n .option('-m, --max <n>', 'Maximum files to return', '10')\n .action(async (options) => {\n if (!options.file && !options.concept) {\n console.log(chalk.red('Either --file or --concept is required'));\n return;\n }\n\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n if (!existsSync(dbPath)) {\n console.log(\n chalk.red('StackMemory not initialized in this directory.')\n );\n return;\n }\n\n const db = new Database(dbPath);\n\n try {\n let projectId = 'default';\n try {\n const row = db\n .prepare(`SELECT value FROM metadata WHERE key = 'project_id'`)\n .get() as any;\n if (row?.value) projectId = row.value;\n } catch {}\n\n const frameManager = new FrameManager(db, projectId, {\n skipContextBridge: true,\n });\n const contextRetrieval = new LLMContextRetrieval(\n db,\n frameManager,\n projectId\n );\n const handlers = new DiscoveryHandlers({\n frameManager,\n contextRetrieval,\n db,\n projectRoot,\n });\n\n const target = options.file || options.concept;\n console.log(chalk.blue(`\\nFinding files related to: ${target}\\n`));\n\n const result = await handlers.handleRelatedFiles({\n file: options.file,\n concept: options.concept,\n maxFiles: parseInt(options.max),\n });\n\n const files = result.metadata.relatedFiles;\n\n if (files.length === 0) {\n console.log(chalk.gray('No related files found.'));\n return;\n }\n\n for (const file of files) {\n const icon =\n file.relevance === 'high'\n ? chalk.green('[HIGH]')\n : chalk.yellow('[MED]');\n console.log(`${icon} ${chalk.white(file.path)}`);\n console.log(chalk.gray(` ${file.reason}`));\n }\n\n console.log('');\n } finally {\n db.close();\n }\n });\n\n // Session summary command\n discovery\n .command('session')\n .alias('s')\n .description('Get current session summary')\n .option('--no-files', 'Exclude recent files')\n .option('--no-decisions', 'Exclude recent decisions')\n .action(async (options) => {\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n if (!existsSync(dbPath)) {\n console.log(\n chalk.red('StackMemory not initialized in this directory.')\n );\n return;\n }\n\n const db = new Database(dbPath);\n\n try {\n let projectId = 'default';\n try {\n const row = db\n .prepare(`SELECT value FROM metadata WHERE key = 'project_id'`)\n .get() as any;\n if (row?.value) projectId = row.value;\n } catch {}\n\n const frameManager = new FrameManager(db, projectId, {\n skipContextBridge: true,\n });\n const contextRetrieval = new LLMContextRetrieval(\n db,\n frameManager,\n projectId\n );\n const handlers = new DiscoveryHandlers({\n frameManager,\n contextRetrieval,\n db,\n projectRoot,\n });\n\n const result = await handlers.handleSessionSummary({\n includeFiles: options.files !== false,\n includeDecisions: options.decisions !== false,\n });\n\n const summary = result.metadata;\n\n console.log(chalk.blue('\\nSession Summary\\n'));\n\n console.log(`${chalk.cyan('Current Goal:')} ${summary.currentGoal}`);\n console.log(`${chalk.cyan('Active Frames:')} ${summary.activeFrames}`);\n console.log(`${chalk.cyan('Stack Depth:')} ${summary.stackDepth}`);\n\n if (summary.recentFiles?.length > 0) {\n console.log(chalk.cyan('\\nRecent Files:'));\n for (const f of summary.recentFiles.slice(0, 10)) {\n console.log(chalk.gray(` - ${f}`));\n }\n }\n\n if (summary.decisions?.length > 0) {\n console.log(chalk.cyan('\\nRecent Decisions:'));\n for (const d of summary.decisions.slice(0, 5)) {\n console.log(\n chalk.gray(\n ` [${d.type}] ${d.text.slice(0, 60)}${d.text.length > 60 ? '...' : ''}`\n )\n );\n }\n }\n\n console.log('');\n } finally {\n db.close();\n }\n });\n\n // Quick context command (default)\n discovery\n .command('quick', { isDefault: true })\n .description('Quick discovery based on current context')\n .action(async () => {\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n if (!existsSync(dbPath)) {\n console.log(\n chalk.red('StackMemory not initialized in this directory.')\n );\n console.log(chalk.gray('Run \"stackmemory init\" first.'));\n return;\n }\n\n const db = new Database(dbPath);\n\n try {\n let projectId = 'default';\n try {\n const row = db\n .prepare(`SELECT value FROM metadata WHERE key = 'project_id'`)\n .get() as any;\n if (row?.value) projectId = row.value;\n } catch {}\n\n const frameManager = new FrameManager(db, projectId, {\n skipContextBridge: true,\n });\n const contextRetrieval = new LLMContextRetrieval(\n db,\n frameManager,\n projectId\n );\n const handlers = new DiscoveryHandlers({\n frameManager,\n contextRetrieval,\n db,\n projectRoot,\n });\n\n console.log(chalk.blue('\\nQuick Discovery\\n'));\n\n // Get session summary first\n const sessionResult = await handlers.handleSessionSummary({\n includeFiles: true,\n includeDecisions: true,\n });\n const session = sessionResult.metadata;\n\n console.log(`${chalk.cyan('Current:')} ${session.currentGoal}`);\n console.log(`${chalk.cyan('Stack:')} ${session.stackDepth} frames`);\n console.log('');\n\n // Quick file discovery\n const discoverResult = await handlers.handleDiscover({\n depth: 'shallow',\n maxFiles: 10,\n });\n const discovery = discoverResult.metadata;\n\n console.log(\n chalk.cyan('Keywords: ') +\n chalk.gray(discovery.keywords.slice(0, 8).join(', '))\n );\n console.log('');\n\n console.log(chalk.cyan('Top Relevant Files:'));\n for (const file of discovery.files.slice(0, 5)) {\n const icon =\n file.relevance === 'high' ? chalk.green('*') : chalk.yellow('-');\n console.log(`${icon} ${file.path}`);\n }\n\n if (session.decisions?.length > 0) {\n console.log('');\n console.log(chalk.cyan('Recent Decisions:'));\n for (const d of session.decisions.slice(0, 3)) {\n console.log(chalk.gray(` [${d.type}] ${d.text.slice(0, 50)}...`));\n }\n }\n\n console.log('');\n console.log(\n chalk.gray('Use \"stackmemory discovery files\" for detailed discovery')\n );\n } finally {\n db.close();\n }\n });\n\n return discovery;\n}\n"],
5
5
  "mappings": ";;;;AAKA,SAAS,eAAe;AACxB,OAAO,cAAc;AACrB,SAAS,YAAY;AACrB,SAAS,kBAAkB;AAC3B,OAAO,WAAW;AAClB,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,yBAAyB;AAE3B,SAAS,0BAAmC;AACjD,QAAM,YAAY,IAAI,QAAQ,WAAW,EACtC,MAAM,UAAU,EAChB,YAAY,kDAAkD;AAGjE,YACG,QAAQ,OAAO,EACf,MAAM,GAAG,EACT,YAAY,4CAA4C,EACxD,OAAO,sBAAsB,mCAAmC,EAChE;AAAA,IACC;AAAA,IACA;AAAA,IACA;AA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AQ,IAAI,MAAM,KAAK,MAAM,EAAE,IAAI,KAAK,EAAE,KAAK,MAAM,GAAG,EAAE,CAAC,KAAK,CAAC;AAAA,QACnE;AAAA,MACF;AAEA,cAAQ,IAAI,EAAE;AACd,cAAQ;AAAA,QACN,MAAM,KAAK,0DAA0D;AAAA,MACvE;AAAA,IACF,UAAE;AACA,SAAG,MAAM;AAAA,IACX;AAAA,EACF,CAAC;AAEH,SAAO;AACT;",
6
6
  "names": ["discovery"]
7
7
  }
@@ -15,7 +15,7 @@ import {
15
15
  import { join } from "path";
16
16
  import Database from "better-sqlite3";
17
17
  import { z } from "zod";
18
- import { FrameManager } from "../../core/context/frame-manager.js";
18
+ import { FrameManager } from "../../core/context/index.js";
19
19
  import { LinearTaskManager } from "../../features/tasks/linear-task-manager.js";
20
20
  import { logger } from "../../core/monitoring/logger.js";
21
21
  import { EnhancedHandoffGenerator } from "../../core/session/enhanced-handoff.js";
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/cli/commands/handoff.ts"],
4
- "sourcesContent": ["/**\n * Handoff command - Commits work and generates a prompt for the next session\n */\n\nimport { Command } from 'commander';\nimport { execSync, execFileSync } from 'child_process';\nimport {\n existsSync,\n readFileSync,\n writeFileSync,\n mkdirSync,\n readdirSync,\n unlinkSync,\n} from 'fs';\nimport { join } from 'path';\nimport Database from 'better-sqlite3';\nimport { z } from 'zod';\nimport { FrameManager } from '../../core/context/frame-manager.js';\nimport { LinearTaskManager } from '../../features/tasks/linear-task-manager.js';\nimport { logger } from '../../core/monitoring/logger.js';\nimport { EnhancedHandoffGenerator } from '../../core/session/enhanced-handoff.js';\n\n// Handoff versioning - keep last N handoffs\nconst MAX_HANDOFF_VERSIONS = 10;\n\nfunction saveVersionedHandoff(\n projectRoot: string,\n branch: string,\n content: string\n): string {\n const handoffsDir = join(projectRoot, '.stackmemory', 'handoffs');\n if (!existsSync(handoffsDir)) {\n mkdirSync(handoffsDir, { recursive: true });\n }\n\n // Generate versioned filename: YYYY-MM-DD-HH-mm-branch.md\n const now = new Date();\n const timestamp = now.toISOString().slice(0, 16).replace(/[T:]/g, '-');\n const safeBranch = branch.replace(/[^a-zA-Z0-9-]/g, '-').slice(0, 30);\n const filename = `${timestamp}-${safeBranch}.md`;\n const versionedPath = join(handoffsDir, filename);\n\n // Save versioned handoff\n writeFileSync(versionedPath, content);\n\n // Clean up old handoffs (keep last N)\n try {\n const files = readdirSync(handoffsDir)\n .filter((f) => f.endsWith('.md'))\n .sort()\n .reverse();\n\n for (const oldFile of files.slice(MAX_HANDOFF_VERSIONS)) {\n unlinkSync(join(handoffsDir, oldFile));\n }\n } catch {\n // Cleanup failed, not critical\n }\n\n return versionedPath;\n}\n\n// Input validation schemas\nconst CommitMessageSchema = z\n .string()\n .min(1, 'Commit message cannot be empty')\n .max(200, 'Commit message too long')\n .regex(\n /^[a-zA-Z0-9\\s\\-_.,:()\\/\\[\\]]+$/,\n 'Commit message contains invalid characters'\n )\n .refine(\n (msg) => !msg.includes('\\n'),\n 'Commit message cannot contain newlines'\n )\n .refine(\n (msg) => !msg.includes('\"'),\n 'Commit message cannot contain double quotes'\n )\n .refine(\n (msg) => !msg.includes('`'),\n 'Commit message cannot contain backticks'\n );\n\nexport function createHandoffCommand(): Command {\n const cmd = new Command('handoff');\n\n cmd.description('Session handoff for continuity between Claude sessions');\n\n // Default action - capture handoff\n cmd\n .command('capture', { isDefault: true })\n .description('Commit current work and generate a handoff prompt')\n .option('-m, --message <message>', 'Custom commit message')\n .option('--no-commit', 'Skip git commit')\n .option('--copy', 'Copy the handoff prompt to clipboard')\n .option('--basic', 'Use basic handoff format instead of enhanced')\n .action(async (options) => {\n try {\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n // 1. Check git status\n let gitStatus = '';\n let hasChanges = false;\n\n try {\n gitStatus = execSync('git status --short', {\n encoding: 'utf-8',\n cwd: projectRoot,\n });\n hasChanges = gitStatus.trim().length > 0;\n } catch {\n console.log('\u26A0\uFE0F Not in a git repository');\n }\n\n // 2. Commit if there are changes and not skipped\n if (hasChanges && options.commit !== false) {\n try {\n // Get current branch\n const currentBranch = execSync('git rev-parse --abbrev-ref HEAD', {\n encoding: 'utf-8',\n cwd: projectRoot,\n }).trim();\n\n // Stage all changes\n execSync('git add -A', { cwd: projectRoot });\n\n // Generate or use custom commit message\n let commitMessage =\n options.message ||\n `chore: handoff checkpoint on ${currentBranch}`;\n\n // Validate commit message\n try {\n commitMessage = CommitMessageSchema.parse(commitMessage);\n } catch (validationError) {\n console.error(\n '\u274C Invalid commit message:',\n (validationError as Error).message\n );\n return;\n }\n\n // Commit using execFileSync for safety\n execFileSync('git', ['commit', '-m', commitMessage], {\n cwd: projectRoot,\n stdio: 'inherit',\n });\n\n console.log(`\u2705 Committed changes: \"${commitMessage}\"`);\n console.log(` Branch: ${currentBranch}`);\n } catch (err: unknown) {\n console.error(\n '\u274C Failed to commit changes:',\n (err as Error).message\n );\n }\n } else if (!hasChanges) {\n console.log('\u2139\uFE0F No changes to commit');\n }\n\n // 3. Gather context for handoff prompt\n let contextSummary = '';\n let tasksSummary = '';\n let recentWork = '';\n\n if (existsSync(dbPath)) {\n const db = new Database(dbPath);\n\n // Get recent context\n const frameManager = new FrameManager(db, 'cli-project');\n const activeFrames = frameManager.getActiveFramePath();\n\n if (activeFrames.length > 0) {\n contextSummary = 'Active context frames:\\n';\n activeFrames.forEach((frame) => {\n contextSummary += ` - ${frame.name} [${frame.type}]\\n`;\n });\n }\n\n // Get task status\n const taskStore = new LinearTaskManager(projectRoot, db);\n const activeTasks = taskStore.getActiveTasks();\n\n const inProgress = activeTasks.filter(\n (t: any) => t.status === 'in_progress'\n );\n const todo = activeTasks.filter((t: any) => t.status === 'pending');\n const recentlyCompleted = activeTasks\n .filter((t: any) => t.status === 'completed' && t.completed_at)\n .sort(\n (a: any, b: any) => (b.completed_at || 0) - (a.completed_at || 0)\n )\n .slice(0, 3);\n\n if (inProgress.length > 0 || todo.length > 0) {\n tasksSummary = '\\nTasks:\\n';\n\n if (inProgress.length > 0) {\n tasksSummary += 'In Progress:\\n';\n inProgress.forEach((t: any) => {\n const externalId = t.external_refs?.linear?.id;\n tasksSummary += ` - ${t.title}${externalId ? ` [${externalId}]` : ''}\\n`;\n });\n }\n\n if (todo.length > 0) {\n tasksSummary += 'TODO:\\n';\n todo.slice(0, 5).forEach((t: any) => {\n const externalId = t.external_refs?.linear?.id;\n tasksSummary += ` - ${t.title}${externalId ? ` [${externalId}]` : ''}\\n`;\n });\n if (todo.length > 5) {\n tasksSummary += ` ... and ${todo.length - 5} more\\n`;\n }\n }\n }\n\n if (recentlyCompleted.length > 0) {\n recentWork = '\\nRecently Completed:\\n';\n recentlyCompleted.forEach((t: any) => {\n recentWork += ` \u2713 ${t.title}\\n`;\n });\n }\n\n // Get recent events\n const recentEvents = db\n .prepare(\n `\n SELECT event_type as type, payload as data, datetime(ts, 'unixepoch') as time\n FROM events\n ORDER BY ts DESC\n LIMIT 5\n `\n )\n .all() as any[];\n\n if (recentEvents.length > 0) {\n recentWork += '\\nRecent Activity:\\n';\n recentEvents.forEach((event) => {\n const data = JSON.parse(event.data);\n recentWork += ` - ${event.type}: ${data.message || data.name || 'activity'}\\n`;\n });\n }\n\n db.close();\n }\n\n // 4. Get current git info\n let gitInfo = '';\n try {\n const branch = execSync('git rev-parse --abbrev-ref HEAD', {\n encoding: 'utf-8',\n cwd: projectRoot,\n }).trim();\n\n const lastCommit = execSync('git log -1 --oneline', {\n encoding: 'utf-8',\n cwd: projectRoot,\n }).trim();\n\n gitInfo = `\\nGit Status:\\n Branch: ${branch}\\n Last commit: ${lastCommit}\\n`;\n } catch {\n // Ignore git errors\n }\n\n // 5. Check for any blockers or notes\n let notes = '';\n const notesPath = join(projectRoot, '.stackmemory', 'handoff.md');\n if (existsSync(notesPath)) {\n const handoffNotes = readFileSync(notesPath, 'utf-8');\n if (handoffNotes.trim()) {\n notes = `\\nNotes from previous handoff:\\n${handoffNotes}\\n`;\n }\n }\n\n // 6. Generate the handoff prompt\n let handoffPrompt: string;\n\n if (options.basic) {\n // Use basic handoff format\n const timestamp = new Date().toISOString();\n handoffPrompt = `# Session Handoff - ${timestamp}\n\n## Project: ${projectRoot.split('/').pop()}\n\n${gitInfo}\n${contextSummary}\n${tasksSummary}\n${recentWork}\n${notes}\n\n## Continue from here:\n\n1. Run \\`stackmemory status\\` to check the current state\n2. Review any in-progress tasks above\n3. Check for any uncommitted changes with \\`git status\\`\n4. Resume work on the active context\n\n## Quick Commands:\n- \\`stackmemory context load --recent\\` - Load recent context\n- \\`stackmemory task list --state in_progress\\` - Show in-progress tasks\n- \\`stackmemory linear sync\\` - Sync with Linear if configured\n- \\`stackmemory log recent\\` - View recent activity\n\n---\nGenerated by stackmemory handoff at ${timestamp}\n`;\n } else {\n // Use high-efficacy enhanced handoff generator (default)\n const enhancedGenerator = new EnhancedHandoffGenerator(projectRoot);\n const enhancedHandoff = await enhancedGenerator.generate();\n handoffPrompt = enhancedGenerator.toMarkdown(enhancedHandoff);\n console.log(`Estimated tokens: ~${enhancedHandoff.estimatedTokens}`);\n }\n\n // 7. Save handoff prompt (both latest and versioned)\n const handoffPath = join(\n projectRoot,\n '.stackmemory',\n 'last-handoff.md'\n );\n writeFileSync(handoffPath, handoffPrompt);\n\n // Save versioned copy\n let branch = 'unknown';\n try {\n branch = execSync('git rev-parse --abbrev-ref HEAD', {\n encoding: 'utf-8',\n cwd: projectRoot,\n }).trim();\n } catch {\n // Not a git repo\n }\n const versionedPath = saveVersionedHandoff(\n projectRoot,\n branch,\n handoffPrompt\n );\n console.log(\n `Versioned: ${versionedPath.split('/').slice(-2).join('/')}`\n );\n\n // 8. Display the prompt\n console.log('\\n' + '='.repeat(60));\n console.log(handoffPrompt);\n console.log('='.repeat(60));\n\n // 9. Copy to clipboard if requested\n if (options.copy) {\n try {\n // Use execFileSync with predefined commands for safety\n if (process.platform === 'darwin') {\n execFileSync('pbcopy', [], {\n input: handoffPrompt,\n cwd: projectRoot,\n });\n } else if (process.platform === 'win32') {\n execFileSync('clip', [], {\n input: handoffPrompt,\n cwd: projectRoot,\n });\n } else {\n execFileSync('xclip', ['-selection', 'clipboard'], {\n input: handoffPrompt,\n cwd: projectRoot,\n });\n }\n\n console.log('\\n\u2705 Handoff prompt copied to clipboard!');\n } catch {\n console.log('\\n\u26A0\uFE0F Could not copy to clipboard');\n }\n }\n\n console.log(`\\n\uD83D\uDCBE Handoff saved to: ${handoffPath}`);\n console.log('\uD83D\uDCCB Use this prompt when starting your next session');\n } catch (error: unknown) {\n logger.error('Handoff command failed', error as Error);\n console.error('\u274C Handoff failed:', (error as Error).message);\n process.exit(1);\n }\n });\n\n // Restore command\n cmd\n .command('restore')\n .description('Restore context from last handoff')\n .option('--no-copy', 'Do not copy prompt to clipboard')\n .action(async (options) => {\n try {\n const projectRoot = process.cwd();\n const handoffPath = join(\n projectRoot,\n '.stackmemory',\n 'last-handoff.md'\n );\n const metaPath = join(\n process.env['HOME'] || '~',\n '.stackmemory',\n 'handoffs',\n 'last-handoff-meta.json'\n );\n\n if (!existsSync(handoffPath)) {\n console.log('\u274C No handoff found in this project');\n console.log('\uD83D\uDCA1 Run \"stackmemory handoff\" to create one');\n return;\n }\n\n // Read handoff prompt\n const handoffPrompt = readFileSync(handoffPath, 'utf-8');\n\n // Display the prompt\n console.log('\\n' + '='.repeat(60));\n console.log('\uD83D\uDCCB RESTORED HANDOFF');\n console.log('='.repeat(60));\n console.log(handoffPrompt);\n console.log('='.repeat(60));\n\n // Check for metadata\n if (existsSync(metaPath)) {\n const metadata = JSON.parse(readFileSync(metaPath, 'utf-8'));\n console.log('\\n\uD83D\uDCCA Session Metadata:');\n console.log(` Timestamp: ${metadata.timestamp}`);\n console.log(` Reason: ${metadata.reason}`);\n console.log(` Duration: ${metadata.session_duration}s`);\n console.log(` Command: ${metadata.command}`);\n }\n\n // Check current git status\n try {\n const gitStatus = execSync('git status --short', {\n encoding: 'utf-8',\n }).trim();\n if (gitStatus) {\n console.log('\\n\u26A0\uFE0F Current uncommitted changes:');\n console.log(gitStatus);\n }\n } catch {\n // Not a git repo\n }\n\n // Copy to clipboard unless disabled\n if (options.copy !== false) {\n try {\n // Use execFileSync with predefined commands for safety\n if (process.platform === 'darwin') {\n execFileSync('pbcopy', [], {\n input: handoffPrompt,\n cwd: projectRoot,\n });\n } else if (process.platform === 'win32') {\n execFileSync('clip', [], {\n input: handoffPrompt,\n cwd: projectRoot,\n });\n } else {\n execFileSync('xclip', ['-selection', 'clipboard'], {\n input: handoffPrompt,\n cwd: projectRoot,\n });\n }\n\n console.log('\\n\u2705 Handoff prompt copied to clipboard!');\n } catch {\n console.log('\\n\u26A0\uFE0F Could not copy to clipboard');\n }\n }\n\n console.log('\\n\uD83D\uDE80 Ready to continue where you left off!');\n } catch (error: unknown) {\n logger.error('Handoff restore failed', error as Error);\n console.error('\u274C Restore failed:', (error as Error).message);\n process.exit(1);\n }\n });\n\n // Auto command - enable auto-capture\n cmd\n .command('auto')\n .description('Enable auto-capture on session termination')\n .option('--command <command>', 'Command to wrap with auto-handoff')\n .action(async (options) => {\n const scriptPath = join(\n __dirname,\n '..',\n '..',\n '..',\n 'scripts',\n 'stackmemory-auto-handoff.sh'\n );\n\n if (!existsSync(scriptPath)) {\n console.error('\u274C Auto-handoff script not found');\n console.log('\uD83D\uDCE6 Please ensure StackMemory is properly installed');\n return;\n }\n\n console.log('\uD83D\uDEE1\uFE0F StackMemory Auto-Handoff');\n console.log('\u2500'.repeat(50));\n\n if (options.command) {\n // Validate and wrap specific command\n const commandSchema = z\n .string()\n .min(1, 'Command cannot be empty')\n .max(200, 'Command too long')\n .regex(\n /^[a-zA-Z0-9\\s\\-_./:]+$/,\n 'Command contains invalid characters'\n )\n .refine((cmd) => !cmd.includes(';'), 'Command cannot contain \";\"')\n .refine((cmd) => !cmd.includes('&'), 'Command cannot contain \"&\"')\n .refine((cmd) => !cmd.includes('|'), 'Command cannot contain \"|\"')\n .refine((cmd) => !cmd.includes('$'), 'Command cannot contain \"$\"')\n .refine((cmd) => !cmd.includes('`'), 'Command cannot contain \"`\"');\n\n try {\n const validatedCommand = commandSchema.parse(options.command);\n console.log(`Wrapping command: ${validatedCommand}`);\n execFileSync(scriptPath, [validatedCommand], {\n stdio: 'inherit',\n env: { ...process.env, AUTO_CAPTURE_ON_EXIT: 'true' },\n });\n } catch (validationError) {\n if (validationError instanceof z.ZodError) {\n console.error('\u274C Invalid command:');\n validationError.errors.forEach((err) => {\n console.error(` ${err.message}`);\n });\n } else {\n console.error(\n '\u274C Failed to execute command:',\n (validationError as Error).message\n );\n }\n return;\n }\n } else {\n // Interactive mode\n console.log('To enable auto-handoff for your current session:');\n console.log('');\n console.log(' For bash/zsh:');\n console.log(` source <(${scriptPath} --shell)`);\n console.log('');\n console.log(' Or wrap a command:');\n console.log(` ${scriptPath} claude`);\n console.log(` ${scriptPath} npm run dev`);\n console.log('');\n console.log(' Add to your shell profile for permanent setup:');\n console.log(\n ` echo 'alias claude=\"${scriptPath} claude\"' >> ~/.bashrc`\n );\n }\n });\n\n return cmd;\n}\n"],
4
+ "sourcesContent": ["/**\n * Handoff command - Commits work and generates a prompt for the next session\n */\n\nimport { Command } from 'commander';\nimport { execSync, execFileSync } from 'child_process';\nimport {\n existsSync,\n readFileSync,\n writeFileSync,\n mkdirSync,\n readdirSync,\n unlinkSync,\n} from 'fs';\nimport { join } from 'path';\nimport Database from 'better-sqlite3';\nimport { z } from 'zod';\nimport { FrameManager } from '../../core/context/index.js';\nimport { LinearTaskManager } from '../../features/tasks/linear-task-manager.js';\nimport { logger } from '../../core/monitoring/logger.js';\nimport { EnhancedHandoffGenerator } from '../../core/session/enhanced-handoff.js';\n\n// Handoff versioning - keep last N handoffs\nconst MAX_HANDOFF_VERSIONS = 10;\n\nfunction saveVersionedHandoff(\n projectRoot: string,\n branch: string,\n content: string\n): string {\n const handoffsDir = join(projectRoot, '.stackmemory', 'handoffs');\n if (!existsSync(handoffsDir)) {\n mkdirSync(handoffsDir, { recursive: true });\n }\n\n // Generate versioned filename: YYYY-MM-DD-HH-mm-branch.md\n const now = new Date();\n const timestamp = now.toISOString().slice(0, 16).replace(/[T:]/g, '-');\n const safeBranch = branch.replace(/[^a-zA-Z0-9-]/g, '-').slice(0, 30);\n const filename = `${timestamp}-${safeBranch}.md`;\n const versionedPath = join(handoffsDir, filename);\n\n // Save versioned handoff\n writeFileSync(versionedPath, content);\n\n // Clean up old handoffs (keep last N)\n try {\n const files = readdirSync(handoffsDir)\n .filter((f) => f.endsWith('.md'))\n .sort()\n .reverse();\n\n for (const oldFile of files.slice(MAX_HANDOFF_VERSIONS)) {\n unlinkSync(join(handoffsDir, oldFile));\n }\n } catch {\n // Cleanup failed, not critical\n }\n\n return versionedPath;\n}\n\n// Input validation schemas\nconst CommitMessageSchema = z\n .string()\n .min(1, 'Commit message cannot be empty')\n .max(200, 'Commit message too long')\n .regex(\n /^[a-zA-Z0-9\\s\\-_.,:()\\/\\[\\]]+$/,\n 'Commit message contains invalid characters'\n )\n .refine(\n (msg) => !msg.includes('\\n'),\n 'Commit message cannot contain newlines'\n )\n .refine(\n (msg) => !msg.includes('\"'),\n 'Commit message cannot contain double quotes'\n )\n .refine(\n (msg) => !msg.includes('`'),\n 'Commit message cannot contain backticks'\n );\n\nexport function createHandoffCommand(): Command {\n const cmd = new Command('handoff');\n\n cmd.description('Session handoff for continuity between Claude sessions');\n\n // Default action - capture handoff\n cmd\n .command('capture', { isDefault: true })\n .description('Commit current work and generate a handoff prompt')\n .option('-m, --message <message>', 'Custom commit message')\n .option('--no-commit', 'Skip git commit')\n .option('--copy', 'Copy the handoff prompt to clipboard')\n .option('--basic', 'Use basic handoff format instead of enhanced')\n .action(async (options) => {\n try {\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n // 1. Check git status\n let gitStatus = '';\n let hasChanges = false;\n\n try {\n gitStatus = execSync('git status --short', {\n encoding: 'utf-8',\n cwd: projectRoot,\n });\n hasChanges = gitStatus.trim().length > 0;\n } catch {\n console.log('\u26A0\uFE0F Not in a git repository');\n }\n\n // 2. Commit if there are changes and not skipped\n if (hasChanges && options.commit !== false) {\n try {\n // Get current branch\n const currentBranch = execSync('git rev-parse --abbrev-ref HEAD', {\n encoding: 'utf-8',\n cwd: projectRoot,\n }).trim();\n\n // Stage all changes\n execSync('git add -A', { cwd: projectRoot });\n\n // Generate or use custom commit message\n let commitMessage =\n options.message ||\n `chore: handoff checkpoint on ${currentBranch}`;\n\n // Validate commit message\n try {\n commitMessage = CommitMessageSchema.parse(commitMessage);\n } catch (validationError) {\n console.error(\n '\u274C Invalid commit message:',\n (validationError as Error).message\n );\n return;\n }\n\n // Commit using execFileSync for safety\n execFileSync('git', ['commit', '-m', commitMessage], {\n cwd: projectRoot,\n stdio: 'inherit',\n });\n\n console.log(`\u2705 Committed changes: \"${commitMessage}\"`);\n console.log(` Branch: ${currentBranch}`);\n } catch (err: unknown) {\n console.error(\n '\u274C Failed to commit changes:',\n (err as Error).message\n );\n }\n } else if (!hasChanges) {\n console.log('\u2139\uFE0F No changes to commit');\n }\n\n // 3. Gather context for handoff prompt\n let contextSummary = '';\n let tasksSummary = '';\n let recentWork = '';\n\n if (existsSync(dbPath)) {\n const db = new Database(dbPath);\n\n // Get recent context\n const frameManager = new FrameManager(db, 'cli-project');\n const activeFrames = frameManager.getActiveFramePath();\n\n if (activeFrames.length > 0) {\n contextSummary = 'Active context frames:\\n';\n activeFrames.forEach((frame) => {\n contextSummary += ` - ${frame.name} [${frame.type}]\\n`;\n });\n }\n\n // Get task status\n const taskStore = new LinearTaskManager(projectRoot, db);\n const activeTasks = taskStore.getActiveTasks();\n\n const inProgress = activeTasks.filter(\n (t: any) => t.status === 'in_progress'\n );\n const todo = activeTasks.filter((t: any) => t.status === 'pending');\n const recentlyCompleted = activeTasks\n .filter((t: any) => t.status === 'completed' && t.completed_at)\n .sort(\n (a: any, b: any) => (b.completed_at || 0) - (a.completed_at || 0)\n )\n .slice(0, 3);\n\n if (inProgress.length > 0 || todo.length > 0) {\n tasksSummary = '\\nTasks:\\n';\n\n if (inProgress.length > 0) {\n tasksSummary += 'In Progress:\\n';\n inProgress.forEach((t: any) => {\n const externalId = t.external_refs?.linear?.id;\n tasksSummary += ` - ${t.title}${externalId ? ` [${externalId}]` : ''}\\n`;\n });\n }\n\n if (todo.length > 0) {\n tasksSummary += 'TODO:\\n';\n todo.slice(0, 5).forEach((t: any) => {\n const externalId = t.external_refs?.linear?.id;\n tasksSummary += ` - ${t.title}${externalId ? ` [${externalId}]` : ''}\\n`;\n });\n if (todo.length > 5) {\n tasksSummary += ` ... and ${todo.length - 5} more\\n`;\n }\n }\n }\n\n if (recentlyCompleted.length > 0) {\n recentWork = '\\nRecently Completed:\\n';\n recentlyCompleted.forEach((t: any) => {\n recentWork += ` \u2713 ${t.title}\\n`;\n });\n }\n\n // Get recent events\n const recentEvents = db\n .prepare(\n `\n SELECT event_type as type, payload as data, datetime(ts, 'unixepoch') as time\n FROM events\n ORDER BY ts DESC\n LIMIT 5\n `\n )\n .all() as any[];\n\n if (recentEvents.length > 0) {\n recentWork += '\\nRecent Activity:\\n';\n recentEvents.forEach((event) => {\n const data = JSON.parse(event.data);\n recentWork += ` - ${event.type}: ${data.message || data.name || 'activity'}\\n`;\n });\n }\n\n db.close();\n }\n\n // 4. Get current git info\n let gitInfo = '';\n try {\n const branch = execSync('git rev-parse --abbrev-ref HEAD', {\n encoding: 'utf-8',\n cwd: projectRoot,\n }).trim();\n\n const lastCommit = execSync('git log -1 --oneline', {\n encoding: 'utf-8',\n cwd: projectRoot,\n }).trim();\n\n gitInfo = `\\nGit Status:\\n Branch: ${branch}\\n Last commit: ${lastCommit}\\n`;\n } catch {\n // Ignore git errors\n }\n\n // 5. Check for any blockers or notes\n let notes = '';\n const notesPath = join(projectRoot, '.stackmemory', 'handoff.md');\n if (existsSync(notesPath)) {\n const handoffNotes = readFileSync(notesPath, 'utf-8');\n if (handoffNotes.trim()) {\n notes = `\\nNotes from previous handoff:\\n${handoffNotes}\\n`;\n }\n }\n\n // 6. Generate the handoff prompt\n let handoffPrompt: string;\n\n if (options.basic) {\n // Use basic handoff format\n const timestamp = new Date().toISOString();\n handoffPrompt = `# Session Handoff - ${timestamp}\n\n## Project: ${projectRoot.split('/').pop()}\n\n${gitInfo}\n${contextSummary}\n${tasksSummary}\n${recentWork}\n${notes}\n\n## Continue from here:\n\n1. Run \\`stackmemory status\\` to check the current state\n2. Review any in-progress tasks above\n3. Check for any uncommitted changes with \\`git status\\`\n4. Resume work on the active context\n\n## Quick Commands:\n- \\`stackmemory context load --recent\\` - Load recent context\n- \\`stackmemory task list --state in_progress\\` - Show in-progress tasks\n- \\`stackmemory linear sync\\` - Sync with Linear if configured\n- \\`stackmemory log recent\\` - View recent activity\n\n---\nGenerated by stackmemory handoff at ${timestamp}\n`;\n } else {\n // Use high-efficacy enhanced handoff generator (default)\n const enhancedGenerator = new EnhancedHandoffGenerator(projectRoot);\n const enhancedHandoff = await enhancedGenerator.generate();\n handoffPrompt = enhancedGenerator.toMarkdown(enhancedHandoff);\n console.log(`Estimated tokens: ~${enhancedHandoff.estimatedTokens}`);\n }\n\n // 7. Save handoff prompt (both latest and versioned)\n const handoffPath = join(\n projectRoot,\n '.stackmemory',\n 'last-handoff.md'\n );\n writeFileSync(handoffPath, handoffPrompt);\n\n // Save versioned copy\n let branch = 'unknown';\n try {\n branch = execSync('git rev-parse --abbrev-ref HEAD', {\n encoding: 'utf-8',\n cwd: projectRoot,\n }).trim();\n } catch {\n // Not a git repo\n }\n const versionedPath = saveVersionedHandoff(\n projectRoot,\n branch,\n handoffPrompt\n );\n console.log(\n `Versioned: ${versionedPath.split('/').slice(-2).join('/')}`\n );\n\n // 8. Display the prompt\n console.log('\\n' + '='.repeat(60));\n console.log(handoffPrompt);\n console.log('='.repeat(60));\n\n // 9. Copy to clipboard if requested\n if (options.copy) {\n try {\n // Use execFileSync with predefined commands for safety\n if (process.platform === 'darwin') {\n execFileSync('pbcopy', [], {\n input: handoffPrompt,\n cwd: projectRoot,\n });\n } else if (process.platform === 'win32') {\n execFileSync('clip', [], {\n input: handoffPrompt,\n cwd: projectRoot,\n });\n } else {\n execFileSync('xclip', ['-selection', 'clipboard'], {\n input: handoffPrompt,\n cwd: projectRoot,\n });\n }\n\n console.log('\\n\u2705 Handoff prompt copied to clipboard!');\n } catch {\n console.log('\\n\u26A0\uFE0F Could not copy to clipboard');\n }\n }\n\n console.log(`\\n\uD83D\uDCBE Handoff saved to: ${handoffPath}`);\n console.log('\uD83D\uDCCB Use this prompt when starting your next session');\n } catch (error: unknown) {\n logger.error('Handoff command failed', error as Error);\n console.error('\u274C Handoff failed:', (error as Error).message);\n process.exit(1);\n }\n });\n\n // Restore command\n cmd\n .command('restore')\n .description('Restore context from last handoff')\n .option('--no-copy', 'Do not copy prompt to clipboard')\n .action(async (options) => {\n try {\n const projectRoot = process.cwd();\n const handoffPath = join(\n projectRoot,\n '.stackmemory',\n 'last-handoff.md'\n );\n const metaPath = join(\n process.env['HOME'] || '~',\n '.stackmemory',\n 'handoffs',\n 'last-handoff-meta.json'\n );\n\n if (!existsSync(handoffPath)) {\n console.log('\u274C No handoff found in this project');\n console.log('\uD83D\uDCA1 Run \"stackmemory handoff\" to create one');\n return;\n }\n\n // Read handoff prompt\n const handoffPrompt = readFileSync(handoffPath, 'utf-8');\n\n // Display the prompt\n console.log('\\n' + '='.repeat(60));\n console.log('\uD83D\uDCCB RESTORED HANDOFF');\n console.log('='.repeat(60));\n console.log(handoffPrompt);\n console.log('='.repeat(60));\n\n // Check for metadata\n if (existsSync(metaPath)) {\n const metadata = JSON.parse(readFileSync(metaPath, 'utf-8'));\n console.log('\\n\uD83D\uDCCA Session Metadata:');\n console.log(` Timestamp: ${metadata.timestamp}`);\n console.log(` Reason: ${metadata.reason}`);\n console.log(` Duration: ${metadata.session_duration}s`);\n console.log(` Command: ${metadata.command}`);\n }\n\n // Check current git status\n try {\n const gitStatus = execSync('git status --short', {\n encoding: 'utf-8',\n }).trim();\n if (gitStatus) {\n console.log('\\n\u26A0\uFE0F Current uncommitted changes:');\n console.log(gitStatus);\n }\n } catch {\n // Not a git repo\n }\n\n // Copy to clipboard unless disabled\n if (options.copy !== false) {\n try {\n // Use execFileSync with predefined commands for safety\n if (process.platform === 'darwin') {\n execFileSync('pbcopy', [], {\n input: handoffPrompt,\n cwd: projectRoot,\n });\n } else if (process.platform === 'win32') {\n execFileSync('clip', [], {\n input: handoffPrompt,\n cwd: projectRoot,\n });\n } else {\n execFileSync('xclip', ['-selection', 'clipboard'], {\n input: handoffPrompt,\n cwd: projectRoot,\n });\n }\n\n console.log('\\n\u2705 Handoff prompt copied to clipboard!');\n } catch {\n console.log('\\n\u26A0\uFE0F Could not copy to clipboard');\n }\n }\n\n console.log('\\n\uD83D\uDE80 Ready to continue where you left off!');\n } catch (error: unknown) {\n logger.error('Handoff restore failed', error as Error);\n console.error('\u274C Restore failed:', (error as Error).message);\n process.exit(1);\n }\n });\n\n // Auto command - enable auto-capture\n cmd\n .command('auto')\n .description('Enable auto-capture on session termination')\n .option('--command <command>', 'Command to wrap with auto-handoff')\n .action(async (options) => {\n const scriptPath = join(\n __dirname,\n '..',\n '..',\n '..',\n 'scripts',\n 'stackmemory-auto-handoff.sh'\n );\n\n if (!existsSync(scriptPath)) {\n console.error('\u274C Auto-handoff script not found');\n console.log('\uD83D\uDCE6 Please ensure StackMemory is properly installed');\n return;\n }\n\n console.log('\uD83D\uDEE1\uFE0F StackMemory Auto-Handoff');\n console.log('\u2500'.repeat(50));\n\n if (options.command) {\n // Validate and wrap specific command\n const commandSchema = z\n .string()\n .min(1, 'Command cannot be empty')\n .max(200, 'Command too long')\n .regex(\n /^[a-zA-Z0-9\\s\\-_./:]+$/,\n 'Command contains invalid characters'\n )\n .refine((cmd) => !cmd.includes(';'), 'Command cannot contain \";\"')\n .refine((cmd) => !cmd.includes('&'), 'Command cannot contain \"&\"')\n .refine((cmd) => !cmd.includes('|'), 'Command cannot contain \"|\"')\n .refine((cmd) => !cmd.includes('$'), 'Command cannot contain \"$\"')\n .refine((cmd) => !cmd.includes('`'), 'Command cannot contain \"`\"');\n\n try {\n const validatedCommand = commandSchema.parse(options.command);\n console.log(`Wrapping command: ${validatedCommand}`);\n execFileSync(scriptPath, [validatedCommand], {\n stdio: 'inherit',\n env: { ...process.env, AUTO_CAPTURE_ON_EXIT: 'true' },\n });\n } catch (validationError) {\n if (validationError instanceof z.ZodError) {\n console.error('\u274C Invalid command:');\n validationError.errors.forEach((err) => {\n console.error(` ${err.message}`);\n });\n } else {\n console.error(\n '\u274C Failed to execute command:',\n (validationError as Error).message\n );\n }\n return;\n }\n } else {\n // Interactive mode\n console.log('To enable auto-handoff for your current session:');\n console.log('');\n console.log(' For bash/zsh:');\n console.log(` source <(${scriptPath} --shell)`);\n console.log('');\n console.log(' Or wrap a command:');\n console.log(` ${scriptPath} claude`);\n console.log(` ${scriptPath} npm run dev`);\n console.log('');\n console.log(' Add to your shell profile for permanent setup:');\n console.log(\n ` echo 'alias claude=\"${scriptPath} claude\"' >> ~/.bashrc`\n );\n }\n });\n\n return cmd;\n}\n"],
5
5
  "mappings": ";;;;AAIA,SAAS,eAAe;AACxB,SAAS,UAAU,oBAAoB;AACvC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY;AACrB,OAAO,cAAc;AACrB,SAAS,SAAS;AAClB,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAClC,SAAS,cAAc;AACvB,SAAS,gCAAgC;AAGzC,MAAM,uBAAuB;AAE7B,SAAS,qBACP,aACA,QACA,SACQ;AACR,QAAM,cAAc,KAAK,aAAa,gBAAgB,UAAU;AAChE,MAAI,CAAC,WAAW,WAAW,GAAG;AAC5B,cAAU,aAAa,EAAE,WAAW,KAAK,CAAC;AAAA,EAC5C;AAGA,QAAM,MAAM,oBAAI,KAAK;AACrB,QAAM,YAAY,IAA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AAC3C,cAAQ,IAAI,EAAE;AACd,cAAQ,IAAI,kDAAkD;AAC9D,cAAQ;AAAA,QACN,2BAA2B,UAAU;AAAA,MACvC;AAAA,IACF;AAAA,EACF,CAAC;AAEH,SAAO;AACT;",
6
6
  "names": ["branch", "cmd"]
7
7
  }
@@ -3,9 +3,7 @@ import { dirname as __pathDirname } from 'path';
3
3
  const __filename = __fileURLToPath(import.meta.url);
4
4
  const __dirname = __pathDirname(__filename);
5
5
  import chalk from "chalk";
6
- import {
7
- LinearAuthManager
8
- } from "../../integrations/linear/auth.js";
6
+ import { LinearAuthManager } from "../../integrations/linear/auth.js";
9
7
  import { LinearOAuthServer } from "../../integrations/linear/oauth-server.js";
10
8
  import {
11
9
  LinearSyncEngine,
@@ -24,17 +22,6 @@ import { join } from "path";
24
22
  import { existsSync } from "fs";
25
23
  import { logger } from "../../core/monitoring/logger.js";
26
24
  import Table from "cli-table3";
27
- function getEnv(key, defaultValue) {
28
- const value = process.env[key];
29
- if (value === void 0) {
30
- if (defaultValue !== void 0) return defaultValue;
31
- throw new Error(`Environment variable ${key} is required`);
32
- }
33
- return value;
34
- }
35
- function getOptionalEnv(key) {
36
- return process.env[key];
37
- }
38
25
  function displaySyncResult(result) {
39
26
  if (result.success) {
40
27
  console.log(chalk.green("\u2713 Sync completed successfully"));
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/cli/commands/linear.ts"],
4
- "sourcesContent": ["/**\n * Linear integration commands\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport {\n LinearAuthManager,\n LinearOAuthSetup,\n} from '../../integrations/linear/auth.js';\nimport { LinearOAuthServer } from '../../integrations/linear/oauth-server.js';\nimport {\n LinearSyncEngine,\n DEFAULT_SYNC_CONFIG,\n} from '../../integrations/linear/sync.js';\nimport {\n LinearSyncManager,\n DEFAULT_SYNC_MANAGER_CONFIG,\n} from '../../integrations/linear/sync-manager.js';\nimport { LinearConfigManager } from '../../integrations/linear/config.js';\nimport { LinearTaskManager } from '../../features/tasks/linear-task-manager.js';\nimport { LinearClient } from '../../integrations/linear/client.js';\nimport { LinearRestClient } from '../../integrations/linear/rest-client.js';\nimport Database from 'better-sqlite3';\nimport { join } from 'path';\nimport { existsSync, mkdirSync } from 'fs';\nimport { logger } from '../../core/monitoring/logger.js';\nimport Table from 'cli-table3';\nimport { SyncResult } from '../../integrations/linear/sync.js';\n// Type-safe environment variable access\nfunction getEnv(key: string, defaultValue?: string): string {\n const value = process.env[key];\n if (value === undefined) {\n if (defaultValue !== undefined) return defaultValue;\n throw new Error(`Environment variable ${key} is required`);\n }\n return value;\n}\n\nfunction getOptionalEnv(key: string): string | undefined {\n return process.env[key];\n}\n\n/**\n * Display sync result in a formatted way\n */\nfunction displaySyncResult(result: SyncResult) {\n if (result.success) {\n console.log(chalk.green('\u2713 Sync completed successfully'));\n } else {\n console.log(chalk.yellow('\u26A0 Sync completed with issues'));\n }\n\n if (\n result.synced.toLinear > 0 ||\n result.synced.fromLinear > 0 ||\n result.synced.updated > 0\n ) {\n console.log(chalk.cyan(' \uD83D\uDCCA Summary:'));\n if (result.synced.toLinear > 0) {\n console.log(` \u2192 Linear: ${result.synced.toLinear} tasks`);\n }\n if (result.synced.fromLinear > 0) {\n console.log(` \u2190 Linear: ${result.synced.fromLinear} tasks`);\n }\n if (result.synced.updated > 0) {\n console.log(` \u2194 Updated: ${result.synced.updated} tasks`);\n }\n }\n\n if (result.conflicts.length > 0) {\n console.log(chalk.yellow(` \u26A0 Conflicts: ${result.conflicts.length}`));\n result.conflicts.slice(0, 3).forEach((conflict) => {\n console.log(` - ${conflict.reason}`);\n });\n if (result.conflicts.length > 3) {\n console.log(` ... and ${result.conflicts.length - 3} more`);\n }\n }\n\n if (result.errors.length > 0) {\n console.log(chalk.red(` \u274C Errors: ${result.errors.length}`));\n result.errors.slice(0, 3).forEach((error) => {\n console.log(` - ${error.substring(0, 80)}`);\n });\n if (result.errors.length > 3) {\n console.log(` ... and ${result.errors.length - 3} more`);\n }\n }\n}\n\nexport function registerLinearCommands(parent: Command) {\n const linear = parent\n .command('linear')\n .description('Linear API integration commands');\n\n // Quick tasks command using memory cache\n linear\n .command('list')\n .alias('ls')\n .description('List Linear tasks (memory-cached)')\n .option('--limit <n>', 'Number of tasks to show', '20')\n .option(\n '--status <status>',\n 'Filter by status (backlog, started, completed, etc.)'\n )\n .option('--my', 'Show only tasks assigned to me')\n .option('--cache', 'Show cache stats only')\n .option('--refresh', 'Force refresh cache')\n .option('--count', 'Show count by status only')\n .action(async (options) => {\n try {\n const apiKey = process.env['LINEAR_API_KEY'];\n if (!apiKey) {\n console.log(\n chalk.yellow('\u26A0 Set LINEAR_API_KEY environment variable')\n );\n return;\n }\n\n const restClient = new LinearRestClient(apiKey);\n\n // Show cache stats if requested\n if (options.cache) {\n const stats = restClient.getCacheStats();\n console.log(chalk.cyan('\uD83D\uDCCA Cache Stats:'));\n console.log(` Size: ${stats.size} tasks`);\n console.log(` Age: ${Math.round(stats.age / 1000)}s`);\n console.log(` Fresh: ${stats.fresh ? 'yes' : 'no'}`);\n console.log(\n ` Last sync: ${new Date(stats.lastSync).toLocaleString()}`\n );\n return;\n }\n\n // Show counts only\n if (options.count) {\n const counts = await restClient.getTaskCounts();\n console.log(chalk.cyan('\uD83D\uDCCA Task Counts:'));\n Object.entries(counts)\n .sort(([, a], [, b]) => b - a)\n .forEach(([status, count]) => {\n console.log(` ${status}: ${count}`);\n });\n return;\n }\n\n let tasks;\n if (options.my) {\n tasks = await restClient.getMyTasks();\n } else if (options.status) {\n tasks = await restClient.getTasksByStatus(options.status);\n } else {\n tasks = await restClient.getAllTasks(options.refresh);\n }\n\n if (!tasks || tasks.length === 0) {\n console.log(chalk.gray('No tasks found'));\n return;\n }\n\n // Limit results\n const limit = parseInt(options.limit);\n const displayTasks = tasks.slice(0, limit);\n\n console.log(\n chalk.cyan(\n `\\n\uD83D\uDCCB Linear Tasks (${displayTasks.length}/${tasks.length}):`\n )\n );\n\n displayTasks.forEach((task) => {\n const priority = task.priority ? `P${task.priority}` : '';\n const assignee = task.assignee ? ` @${task.assignee.name}` : '';\n const statusColor =\n task.state.type === 'completed'\n ? chalk.green\n : task.state.type === 'started'\n ? chalk.yellow\n : chalk.gray;\n\n console.log(`${chalk.blue(task.identifier)} ${task.title}`);\n console.log(\n chalk.gray(\n ` ${statusColor(task.state.name)} ${priority}${assignee}`\n )\n );\n });\n\n console.log(\n chalk.gray(\n `\\n${displayTasks.length} shown, ${tasks.length} total tasks`\n )\n );\n } catch (error: unknown) {\n console.error(\n chalk.red('Failed to list tasks:'),\n (error as Error).message\n );\n }\n });\n\n // Auth command\n linear\n .command('auth')\n .description('Authenticate with Linear')\n .option('--api-key <key>', 'Use API key instead of OAuth')\n .option('--no-browser', 'Do not open browser automatically')\n .action(async (options) => {\n try {\n if (options.apiKey) {\n // Set API key as environment variable\n process.env['LINEAR_API_KEY'] = options.apiKey;\n console.log(chalk.green('\u2713 Linear API key set'));\n\n // Test the connection\n const client = new LinearClient({ apiKey: options.apiKey });\n const user = await client.getViewer();\n\n if (user) {\n console.log(\n chalk.cyan(`Connected as: ${user.name} (${user.email})`)\n );\n }\n } else {\n // OAuth flow with callback server\n const authManager = new LinearAuthManager(process.cwd());\n\n // Check if client ID and secret are configured\n const clientId = process.env['LINEAR_CLIENT_ID'];\n const clientSecret = process.env['LINEAR_CLIENT_SECRET'];\n\n if (!clientId || !clientSecret) {\n console.log(chalk.yellow('\\n\u26A0 Linear OAuth app not configured'));\n console.log(chalk.cyan('\\n\uD83D\uDCDD Setup Instructions:'));\n console.log(\n ' 1. Create a Linear OAuth app at: https://linear.app/settings/api'\n );\n console.log(\n ' 2. Set redirect URI to: http://localhost:3456/auth/linear/callback'\n );\n console.log(' 3. Copy your Client ID and Client Secret');\n console.log(' 4. Set environment variables:');\n console.log(\n chalk.gray(' export LINEAR_CLIENT_ID=\"your_client_id\"')\n );\n console.log(\n chalk.gray(\n ' export LINEAR_CLIENT_SECRET=\"your_client_secret\"'\n )\n );\n console.log(' 5. Run this command again');\n return;\n }\n\n // Save OAuth config\n authManager.saveConfig({\n clientId,\n clientSecret,\n redirectUri: 'http://localhost:3456/auth/linear/callback',\n scopes: ['read', 'write', 'admin'],\n });\n\n // Start OAuth server\n const oauthServer = new LinearOAuthServer(process.cwd());\n const { url } = await oauthServer.start();\n\n // Open browser if not disabled\n if (options.browser !== false) {\n const open = (await import('open')).default;\n await open(url);\n console.log(\n chalk.green('\\n\u2713 Browser opened with authorization page')\n );\n } else {\n console.log(chalk.cyan('\\n\uD83D\uDD17 Open this URL in your browser:'));\n console.log(chalk.underline(url));\n }\n\n console.log(chalk.gray('\\nWaiting for authorization...'));\n console.log(\n chalk.gray(\n 'The server will automatically shut down after authorization.'\n )\n );\n }\n } catch (error: unknown) {\n console.error(\n chalk.red('Authentication failed:'),\n (error as Error).message\n );\n process.exit(1);\n }\n });\n\n // Sync command\n linear\n .command('sync')\n .description('Sync tasks with Linear')\n .option(\n '-d, --direction <dir>',\n 'Sync direction: bidirectional, to_linear, from_linear',\n 'bidirectional'\n )\n .option('-t, --team <id>', 'Default Linear team ID')\n .option('--dry-run', 'Preview sync without making changes')\n .option('--daemon', 'Run in daemon mode with periodic sync')\n .option(\n '-i, --interval <minutes>',\n 'Sync interval in minutes (default: 15)'\n )\n .action(async (options) => {\n try {\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n if (!existsSync(dbPath)) {\n console.log(chalk.red('\u274C StackMemory not initialized'));\n return;\n }\n\n const db = new Database(dbPath);\n const taskStore = new LinearTaskManager(projectRoot, db);\n const authManager = new LinearAuthManager(projectRoot);\n\n const config = {\n ...DEFAULT_SYNC_CONFIG,\n direction: options.direction,\n defaultTeamId: options.team,\n enabled: true,\n };\n\n if (options.daemon) {\n // Run in daemon mode with periodic sync\n const managerConfig = {\n ...DEFAULT_SYNC_MANAGER_CONFIG,\n ...config,\n autoSyncInterval: parseInt(options.interval) || 15,\n };\n\n const syncManager = new LinearSyncManager(\n taskStore,\n authManager,\n managerConfig,\n projectRoot\n );\n\n console.log(chalk.green('\uD83D\uDE80 Starting Linear sync daemon'));\n console.log(\n chalk.cyan(\n ` Sync interval: ${managerConfig.autoSyncInterval} minutes`\n )\n );\n console.log(chalk.cyan(` Direction: ${managerConfig.direction}`));\n console.log(chalk.gray(' Press Ctrl+C to stop\\n'));\n\n // Initial sync\n const initialResult = await syncManager.syncOnStart();\n if (initialResult) {\n displaySyncResult(initialResult);\n }\n\n // Listen for sync events\n syncManager.on('sync:started', ({ trigger }) => {\n console.log(\n chalk.yellow(\n `\\n\uD83D\uDD04 ${new Date().toLocaleTimeString()} - Starting ${trigger} sync...`\n )\n );\n });\n\n syncManager.on('sync:completed', ({ result }) => {\n displaySyncResult(result);\n });\n\n syncManager.on('sync:failed', ({ result }) => {\n console.log(chalk.red('\u274C Sync failed'));\n if (result.errors.length > 0) {\n result.errors.forEach((error: string) => {\n console.log(chalk.red(` - ${error}`));\n });\n }\n });\n\n // Handle graceful shutdown\n process.on('SIGINT', async () => {\n console.log(chalk.yellow('\\n\u23F9 Stopping sync daemon...'));\n await syncManager.syncOnEnd();\n syncManager.stop();\n db.close();\n process.exit(0);\n });\n\n // Keep process alive\n process.stdin.resume();\n } else {\n // Single sync\n const syncEngine = new LinearSyncEngine(\n taskStore,\n authManager,\n config\n );\n\n console.log(chalk.yellow('\uD83D\uDD04 Syncing with Linear...'));\n\n if (options.dryRun) {\n console.log(chalk.gray('(Dry run - no changes will be made)'));\n }\n\n const result = await syncEngine.sync();\n displaySyncResult(result);\n db.close();\n }\n } catch (error: unknown) {\n logger.error('Sync failed', error as Error);\n console.error(chalk.red('Sync failed:'), (error as Error).message);\n process.exit(1);\n }\n });\n\n // Status command\n linear\n .command('status')\n .description('Show Linear sync status')\n .action(async () => {\n try {\n const authManager = new LinearAuthManager(process.cwd());\n const tokens = authManager.loadTokens();\n const apiKey = process.env['LINEAR_API_KEY'];\n\n if (!tokens && !apiKey) {\n console.log(chalk.yellow('\u26A0 Not authenticated with Linear'));\n console.log('Run \"stackmemory linear auth\" to connect');\n return;\n }\n\n const client = apiKey\n ? new LinearClient({ apiKey })\n : new LinearClient({\n apiKey: tokens!.accessToken,\n useBearer: true,\n onUnauthorized: async () => {\n const refreshed = await authManager.refreshAccessToken();\n return refreshed.accessToken;\n },\n });\n\n const user = await client.getViewer();\n\n if (user) {\n console.log(chalk.green('\u2713 Connected to Linear'));\n console.log(chalk.cyan(` User: ${user.name} (${user.email})`));\n\n // Show teams\n const teams = await client.getTeams();\n if (teams && teams.length > 0) {\n console.log(chalk.cyan('\\n\uD83D\uDCCB Teams:'));\n teams.forEach((team) => {\n console.log(` - ${team.name} (${team.key})`);\n });\n }\n } else {\n console.log(chalk.red('\u274C Could not connect to Linear'));\n }\n } catch (error: unknown) {\n console.error(\n chalk.red('Status check failed:'),\n (error as Error).message\n );\n }\n });\n\n // List tasks command\n linear\n .command('tasks')\n .description('List Linear tasks')\n .option('--limit <n>', 'Number of tasks to show', '50')\n .option(\n '--status <status>',\n 'Filter by status (backlog, started, completed, etc.)'\n )\n .option('--my', 'Show only tasks assigned to me')\n .option('--cache', 'Show cache stats')\n .option('--refresh', 'Force refresh cache')\n .action(async (options) => {\n try {\n const apiKey = process.env['LINEAR_API_KEY'];\n if (!apiKey) {\n console.log(\n chalk.yellow('\u26A0 Set LINEAR_API_KEY environment variable')\n );\n return;\n }\n\n const restClient = new LinearRestClient(apiKey);\n\n // Show cache stats if requested\n if (options.cache) {\n const stats = restClient.getCacheStats();\n console.log(chalk.cyan('\uD83D\uDCCA Cache Stats:'));\n console.log(` Size: ${stats.size} tasks`);\n console.log(` Age: ${Math.round(stats.age / 1000)}s`);\n console.log(` Fresh: ${stats.fresh ? 'yes' : 'no'}`);\n console.log(\n ` Last sync: ${new Date(stats.lastSync).toLocaleString()}`\n );\n return;\n }\n\n let tasks;\n if (options.my) {\n tasks = await restClient.getMyTasks();\n } else if (options.status) {\n tasks = await restClient.getTasksByStatus(options.status);\n } else {\n tasks = await restClient.getAllTasks(options.refresh);\n }\n\n if (!tasks || tasks.length === 0) {\n console.log(chalk.gray('No tasks found'));\n return;\n }\n\n // Limit results\n const limit = parseInt(options.limit);\n const displayTasks = tasks.slice(0, limit);\n\n const table = new Table({\n head: ['ID', 'Title', 'State', 'Priority', 'Assignee'],\n style: { head: ['cyan'] },\n });\n\n displayTasks.forEach((task) => {\n table.push([\n task.identifier,\n task.title.substring(0, 40) + (task.title.length > 40 ? '...' : ''),\n task.state?.name || '-',\n task.priority ? `P${task.priority}` : '-',\n task.assignee?.name || '-',\n ]);\n });\n\n console.log(table.toString());\n\n // Show counts by status\n const counts = await restClient.getTaskCounts();\n console.log(chalk.cyan('\\n\uD83D\uDCCA Task Summary:'));\n Object.entries(counts).forEach(([status, count]) => {\n console.log(` ${status}: ${count}`);\n });\n\n console.log(\n chalk.gray(\n `\\nShowing ${displayTasks.length} of ${tasks.length} total tasks`\n )\n );\n\n const cacheStats = restClient.getCacheStats();\n console.log(\n chalk.gray(\n `Cache: ${cacheStats.size} tasks, age: ${Math.round(cacheStats.age / 1000)}s`\n )\n );\n } catch (error: unknown) {\n console.error(\n chalk.red('Failed to list tasks:'),\n (error as Error).message\n );\n }\n });\n\n // Update command - update Linear task status\n linear\n .command('update <issueId>')\n .description('Update Linear task status')\n .option(\n '-s, --status <status>',\n 'New status (todo, in-progress, done, canceled)'\n )\n .option('-t, --title <title>', 'Update task title')\n .option('-d, --description <desc>', 'Update task description')\n .option(\n '-p, --priority <priority>',\n 'Set priority (1=urgent, 2=high, 3=medium, 4=low)'\n )\n .action(async (issueId, options) => {\n try {\n const authManager = new LinearAuthManager(process.cwd());\n const tokens = authManager.loadTokens();\n\n if (!tokens) {\n console.error(\n chalk.red('Not authenticated. Run: stackmemory linear auth')\n );\n return;\n }\n\n const client = new LinearClient({\n apiKey: tokens.accessToken,\n });\n\n // Find the issue first\n let issue = await client.getIssue(issueId);\n if (!issue) {\n // Try finding by identifier\n issue = await client.findIssueByIdentifier(issueId);\n }\n\n if (!issue) {\n console.error(chalk.red(`Issue ${issueId} not found`));\n return;\n }\n\n const updates: any = {};\n\n // Handle status update\n if (options.status) {\n const team = await client.getTeam();\n const states = await client.getWorkflowStates(team.id);\n\n const statusMap: Record<string, string> = {\n todo: 'unstarted',\n 'in-progress': 'started',\n done: 'completed',\n canceled: 'cancelled',\n };\n\n const targetType =\n statusMap[options.status.toLowerCase()] || options.status;\n const targetState = states.find((s) => s.type === targetType);\n\n if (!targetState) {\n console.error(chalk.red(`Invalid status: ${options.status}`));\n console.log(chalk.gray('Available states:'));\n states.forEach((s) =>\n console.log(chalk.gray(` - ${s.name} (${s.type})`))\n );\n return;\n }\n\n updates.stateId = targetState.id;\n }\n\n if (options.title) updates.title = options.title;\n if (options.description) updates.description = options.description;\n if (options.priority) updates.priority = parseInt(options.priority);\n\n // Perform update\n const updatedIssue = await client.updateIssue(issue.id, updates);\n\n console.log(\n chalk.green(\n `\u2713 Updated ${updatedIssue.identifier}: ${updatedIssue.title}`\n )\n );\n if (options.status) {\n console.log(chalk.cyan(` Status: ${updatedIssue.state.name}`));\n }\n console.log(chalk.gray(` ${updatedIssue.url}`));\n } catch (error: unknown) {\n console.error(\n chalk.red('Failed to update task:'),\n (error as Error).message\n );\n }\n });\n\n // Config command\n linear\n .command('config')\n .description('Configure Linear sync settings')\n .option('--team <id>', 'Set default team ID')\n .option('--interval <minutes>', 'Auto-sync interval in minutes')\n .option('--direction <dir>', 'Sync direction')\n .option('--conflict <strategy>', 'Conflict resolution strategy')\n .action(async (options) => {\n try {\n const configManager = new LinearConfigManager(process.cwd());\n const config =\n configManager.loadConfig() || configManager.getDefaultConfig();\n\n let updated = false;\n\n if (options.team) {\n // Team ID would need to be stored separately or in a different config\n logger.info('Team ID configuration not yet implemented', {\n teamId: options.team,\n });\n }\n\n if (options.interval) {\n config.interval = parseInt(options.interval);\n updated = true;\n }\n\n if (options.direction) {\n config.direction = options.direction;\n updated = true;\n }\n\n if (options.conflict) {\n config.conflictResolution = options.conflict;\n updated = true;\n }\n\n if (updated) {\n configManager.saveConfig(config);\n console.log(chalk.green('\u2713 Configuration updated'));\n }\n\n // Display current config\n console.log(chalk.cyan('\\n\uD83D\uDCCB Current Configuration:'));\n console.log(` Enabled: ${config.enabled ? 'yes' : 'no'}`);\n console.log(` Interval: ${config.interval} minutes`);\n console.log(` Direction: ${config.direction}`);\n console.log(` Conflicts: ${config.conflictResolution}`);\n } catch (error: unknown) {\n console.error(chalk.red('Config failed:'), (error as Error).message);\n }\n });\n}\n"],
5
- "mappings": ";;;;AAKA,OAAO,WAAW;AAClB;AAAA,EACE;AAAA,OAEK;AACP,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,OAAO,cAAc;AACrB,SAAS,YAAY;AACrB,SAAS,kBAA6B;AACtC,SAAS,cAAc;AACvB,OAAO,WAAW;AAGlB,SAAS,OAAO,KAAa,cAA+B;AAC1D,QAAM,QAAQ,QAAQ,IAAI,GAAG;AAC7B,MAAI,UAAU,QAAW;AACvB,QAAI,iBAAiB,OAAW,QAAO;AACvC,UAAM,IAAI,MAAM,wBAAwB,GAAG,cAAc;AAAA,EAC3D;AACA,SAAO;AACT;AAEA,SAAS,eAAe,KAAiC;AACvD,SAAO,QAAQ,IAAI,GAAG;AACxB;AAKA,SAAS,kBAAkB,QAAoB;AAC7C,MAAI,OAAO,SAAS;AAClB,YAAQ,IAAI,MAAM,MAAM,oCAA+B,CAAC;AAAA,EAC1D,OAAO;AACL,YAAQ,IAAI,MAAM,OAAO,mCAA8B,CAAC;AAAA,EAC1D;AAEA,MACE,OAAO,OAAO,WAAW,KACzB,OAAO,OAAO,aAAa,KAC3B,OAAO,OAAO,UAAU,GACxB;AACA,YAAQ,IAAI,M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AI,oBAAoB,QAAQ,IAAI,CAAC;AAC3D,YAAM,SACJ,cAAc,WAAW,KAAK,cAAc,iBAAiB;AAE/D,UAAI,UAAU;AAEd,UAAI,QAAQ,MAAM;AAEhB,eAAO,KAAK,6CAA6C;AAAA,UACvD,QAAQ,QAAQ;AAAA,QAClB,CAAC;AAAA,MACH;AAEA,UAAI,QAAQ,UAAU;AACpB,eAAO,WAAW,SAAS,QAAQ,QAAQ;AAC3C,kBAAU;AAAA,MACZ;AAEA,UAAI,QAAQ,WAAW;AACrB,eAAO,YAAY,QAAQ;AAC3B,kBAAU;AAAA,MACZ;AAEA,UAAI,QAAQ,UAAU;AACpB,eAAO,qBAAqB,QAAQ;AACpC,kBAAU;AAAA,MACZ;AAEA,UAAI,SAAS;AACX,sBAAc,WAAW,MAAM;AAC/B,gBAAQ,IAAI,MAAM,MAAM,8BAAyB,CAAC;AAAA,MACpD;AAGA,cAAQ,IAAI,MAAM,KAAK,oCAA6B,CAAC;AACrD,cAAQ,IAAI,cAAc,OAAO,UAAU,QAAQ,IAAI,EAAE;AACzD,cAAQ,IAAI,eAAe,OAAO,QAAQ,UAAU;AACpD,cAAQ,IAAI,gBAAgB,OAAO,SAAS,EAAE;AAC9C,cAAQ,IAAI,gBAAgB,OAAO,kBAAkB,EAAE;AAAA,IACzD,SAAS,OAAgB;AACvB,cAAQ,MAAM,MAAM,IAAI,gBAAgB,GAAI,MAAgB,OAAO;AAAA,IACrE;AAAA,EACF,CAAC;AACL;",
4
+ "sourcesContent": ["/**\n * Linear integration commands\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { LinearAuthManager } from '../../integrations/linear/auth.js';\nimport { LinearOAuthServer } from '../../integrations/linear/oauth-server.js';\nimport {\n LinearSyncEngine,\n DEFAULT_SYNC_CONFIG,\n} from '../../integrations/linear/sync.js';\nimport {\n LinearSyncManager,\n DEFAULT_SYNC_MANAGER_CONFIG,\n} from '../../integrations/linear/sync-manager.js';\nimport { LinearConfigManager } from '../../integrations/linear/config.js';\nimport { LinearTaskManager } from '../../features/tasks/linear-task-manager.js';\nimport { LinearClient } from '../../integrations/linear/client.js';\nimport { LinearRestClient } from '../../integrations/linear/rest-client.js';\nimport Database from 'better-sqlite3';\nimport { join } from 'path';\nimport { existsSync } from 'fs';\nimport { logger } from '../../core/monitoring/logger.js';\nimport Table from 'cli-table3';\nimport { SyncResult } from '../../integrations/linear/sync.js';\n\n// Type-safe environment variable access\n\n/**\n * Display sync result in a formatted way\n */\nfunction displaySyncResult(result: SyncResult) {\n if (result.success) {\n console.log(chalk.green('\u2713 Sync completed successfully'));\n } else {\n console.log(chalk.yellow('\u26A0 Sync completed with issues'));\n }\n\n if (\n result.synced.toLinear > 0 ||\n result.synced.fromLinear > 0 ||\n result.synced.updated > 0\n ) {\n console.log(chalk.cyan(' \uD83D\uDCCA Summary:'));\n if (result.synced.toLinear > 0) {\n console.log(` \u2192 Linear: ${result.synced.toLinear} tasks`);\n }\n if (result.synced.fromLinear > 0) {\n console.log(` \u2190 Linear: ${result.synced.fromLinear} tasks`);\n }\n if (result.synced.updated > 0) {\n console.log(` \u2194 Updated: ${result.synced.updated} tasks`);\n }\n }\n\n if (result.conflicts.length > 0) {\n console.log(chalk.yellow(` \u26A0 Conflicts: ${result.conflicts.length}`));\n result.conflicts.slice(0, 3).forEach((conflict) => {\n console.log(` - ${conflict.reason}`);\n });\n if (result.conflicts.length > 3) {\n console.log(` ... and ${result.conflicts.length - 3} more`);\n }\n }\n\n if (result.errors.length > 0) {\n console.log(chalk.red(` \u274C Errors: ${result.errors.length}`));\n result.errors.slice(0, 3).forEach((error) => {\n console.log(` - ${error.substring(0, 80)}`);\n });\n if (result.errors.length > 3) {\n console.log(` ... and ${result.errors.length - 3} more`);\n }\n }\n}\n\nexport function registerLinearCommands(parent: Command) {\n const linear = parent\n .command('linear')\n .description('Linear API integration commands');\n\n // Quick tasks command using memory cache\n linear\n .command('list')\n .alias('ls')\n .description('List Linear tasks (memory-cached)')\n .option('--limit <n>', 'Number of tasks to show', '20')\n .option(\n '--status <status>',\n 'Filter by status (backlog, started, completed, etc.)'\n )\n .option('--my', 'Show only tasks assigned to me')\n .option('--cache', 'Show cache stats only')\n .option('--refresh', 'Force refresh cache')\n .option('--count', 'Show count by status only')\n .action(async (options) => {\n try {\n const apiKey = process.env['LINEAR_API_KEY'];\n if (!apiKey) {\n console.log(\n chalk.yellow('\u26A0 Set LINEAR_API_KEY environment variable')\n );\n return;\n }\n\n const restClient = new LinearRestClient(apiKey);\n\n // Show cache stats if requested\n if (options.cache) {\n const stats = restClient.getCacheStats();\n console.log(chalk.cyan('\uD83D\uDCCA Cache Stats:'));\n console.log(` Size: ${stats.size} tasks`);\n console.log(` Age: ${Math.round(stats.age / 1000)}s`);\n console.log(` Fresh: ${stats.fresh ? 'yes' : 'no'}`);\n console.log(\n ` Last sync: ${new Date(stats.lastSync).toLocaleString()}`\n );\n return;\n }\n\n // Show counts only\n if (options.count) {\n const counts = await restClient.getTaskCounts();\n console.log(chalk.cyan('\uD83D\uDCCA Task Counts:'));\n Object.entries(counts)\n .sort(([, a], [, b]) => b - a)\n .forEach(([status, count]) => {\n console.log(` ${status}: ${count}`);\n });\n return;\n }\n\n let tasks;\n if (options.my) {\n tasks = await restClient.getMyTasks();\n } else if (options.status) {\n tasks = await restClient.getTasksByStatus(options.status);\n } else {\n tasks = await restClient.getAllTasks(options.refresh);\n }\n\n if (!tasks || tasks.length === 0) {\n console.log(chalk.gray('No tasks found'));\n return;\n }\n\n // Limit results\n const limit = parseInt(options.limit);\n const displayTasks = tasks.slice(0, limit);\n\n console.log(\n chalk.cyan(\n `\\n\uD83D\uDCCB Linear Tasks (${displayTasks.length}/${tasks.length}):`\n )\n );\n\n displayTasks.forEach((task) => {\n const priority = task.priority ? `P${task.priority}` : '';\n const assignee = task.assignee ? ` @${task.assignee.name}` : '';\n const statusColor =\n task.state.type === 'completed'\n ? chalk.green\n : task.state.type === 'started'\n ? chalk.yellow\n : chalk.gray;\n\n console.log(`${chalk.blue(task.identifier)} ${task.title}`);\n console.log(\n chalk.gray(\n ` ${statusColor(task.state.name)} ${priority}${assignee}`\n )\n );\n });\n\n console.log(\n chalk.gray(\n `\\n${displayTasks.length} shown, ${tasks.length} total tasks`\n )\n );\n } catch (error: unknown) {\n console.error(\n chalk.red('Failed to list tasks:'),\n (error as Error).message\n );\n }\n });\n\n // Auth command\n linear\n .command('auth')\n .description('Authenticate with Linear')\n .option('--api-key <key>', 'Use API key instead of OAuth')\n .option('--no-browser', 'Do not open browser automatically')\n .action(async (options) => {\n try {\n if (options.apiKey) {\n // Set API key as environment variable\n process.env['LINEAR_API_KEY'] = options.apiKey;\n console.log(chalk.green('\u2713 Linear API key set'));\n\n // Test the connection\n const client = new LinearClient({ apiKey: options.apiKey });\n const user = await client.getViewer();\n\n if (user) {\n console.log(\n chalk.cyan(`Connected as: ${user.name} (${user.email})`)\n );\n }\n } else {\n // OAuth flow with callback server\n const authManager = new LinearAuthManager(process.cwd());\n\n // Check if client ID and secret are configured\n const clientId = process.env['LINEAR_CLIENT_ID'];\n const clientSecret = process.env['LINEAR_CLIENT_SECRET'];\n\n if (!clientId || !clientSecret) {\n console.log(chalk.yellow('\\n\u26A0 Linear OAuth app not configured'));\n console.log(chalk.cyan('\\n\uD83D\uDCDD Setup Instructions:'));\n console.log(\n ' 1. Create a Linear OAuth app at: https://linear.app/settings/api'\n );\n console.log(\n ' 2. Set redirect URI to: http://localhost:3456/auth/linear/callback'\n );\n console.log(' 3. Copy your Client ID and Client Secret');\n console.log(' 4. Set environment variables:');\n console.log(\n chalk.gray(' export LINEAR_CLIENT_ID=\"your_client_id\"')\n );\n console.log(\n chalk.gray(\n ' export LINEAR_CLIENT_SECRET=\"your_client_secret\"'\n )\n );\n console.log(' 5. Run this command again');\n return;\n }\n\n // Save OAuth config\n authManager.saveConfig({\n clientId,\n clientSecret,\n redirectUri: 'http://localhost:3456/auth/linear/callback',\n scopes: ['read', 'write', 'admin'],\n });\n\n // Start OAuth server\n const oauthServer = new LinearOAuthServer(process.cwd());\n const { url } = await oauthServer.start();\n\n // Open browser if not disabled\n if (options.browser !== false) {\n const open = (await import('open')).default;\n await open(url);\n console.log(\n chalk.green('\\n\u2713 Browser opened with authorization page')\n );\n } else {\n console.log(chalk.cyan('\\n\uD83D\uDD17 Open this URL in your browser:'));\n console.log(chalk.underline(url));\n }\n\n console.log(chalk.gray('\\nWaiting for authorization...'));\n console.log(\n chalk.gray(\n 'The server will automatically shut down after authorization.'\n )\n );\n }\n } catch (error: unknown) {\n console.error(\n chalk.red('Authentication failed:'),\n (error as Error).message\n );\n process.exit(1);\n }\n });\n\n // Sync command\n linear\n .command('sync')\n .description('Sync tasks with Linear')\n .option(\n '-d, --direction <dir>',\n 'Sync direction: bidirectional, to_linear, from_linear',\n 'bidirectional'\n )\n .option('-t, --team <id>', 'Default Linear team ID')\n .option('--dry-run', 'Preview sync without making changes')\n .option('--daemon', 'Run in daemon mode with periodic sync')\n .option(\n '-i, --interval <minutes>',\n 'Sync interval in minutes (default: 15)'\n )\n .action(async (options) => {\n try {\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n if (!existsSync(dbPath)) {\n console.log(chalk.red('\u274C StackMemory not initialized'));\n return;\n }\n\n const db = new Database(dbPath);\n const taskStore = new LinearTaskManager(projectRoot, db);\n const authManager = new LinearAuthManager(projectRoot);\n\n const config = {\n ...DEFAULT_SYNC_CONFIG,\n direction: options.direction,\n defaultTeamId: options.team,\n enabled: true,\n };\n\n if (options.daemon) {\n // Run in daemon mode with periodic sync\n const managerConfig = {\n ...DEFAULT_SYNC_MANAGER_CONFIG,\n ...config,\n autoSyncInterval: parseInt(options.interval) || 15,\n };\n\n const syncManager = new LinearSyncManager(\n taskStore,\n authManager,\n managerConfig,\n projectRoot\n );\n\n console.log(chalk.green('\uD83D\uDE80 Starting Linear sync daemon'));\n console.log(\n chalk.cyan(\n ` Sync interval: ${managerConfig.autoSyncInterval} minutes`\n )\n );\n console.log(chalk.cyan(` Direction: ${managerConfig.direction}`));\n console.log(chalk.gray(' Press Ctrl+C to stop\\n'));\n\n // Initial sync\n const initialResult = await syncManager.syncOnStart();\n if (initialResult) {\n displaySyncResult(initialResult);\n }\n\n // Listen for sync events\n syncManager.on('sync:started', ({ trigger }) => {\n console.log(\n chalk.yellow(\n `\\n\uD83D\uDD04 ${new Date().toLocaleTimeString()} - Starting ${trigger} sync...`\n )\n );\n });\n\n syncManager.on('sync:completed', ({ result }) => {\n displaySyncResult(result);\n });\n\n syncManager.on('sync:failed', ({ result }) => {\n console.log(chalk.red('\u274C Sync failed'));\n if (result.errors.length > 0) {\n result.errors.forEach((error: string) => {\n console.log(chalk.red(` - ${error}`));\n });\n }\n });\n\n // Handle graceful shutdown\n process.on('SIGINT', async () => {\n console.log(chalk.yellow('\\n\u23F9 Stopping sync daemon...'));\n await syncManager.syncOnEnd();\n syncManager.stop();\n db.close();\n process.exit(0);\n });\n\n // Keep process alive\n process.stdin.resume();\n } else {\n // Single sync\n const syncEngine = new LinearSyncEngine(\n taskStore,\n authManager,\n config\n );\n\n console.log(chalk.yellow('\uD83D\uDD04 Syncing with Linear...'));\n\n if (options.dryRun) {\n console.log(chalk.gray('(Dry run - no changes will be made)'));\n }\n\n const result = await syncEngine.sync();\n displaySyncResult(result);\n db.close();\n }\n } catch (error: unknown) {\n logger.error('Sync failed', error as Error);\n console.error(chalk.red('Sync failed:'), (error as Error).message);\n process.exit(1);\n }\n });\n\n // Status command\n linear\n .command('status')\n .description('Show Linear sync status')\n .action(async () => {\n try {\n const authManager = new LinearAuthManager(process.cwd());\n const tokens = authManager.loadTokens();\n const apiKey = process.env['LINEAR_API_KEY'];\n\n if (!tokens && !apiKey) {\n console.log(chalk.yellow('\u26A0 Not authenticated with Linear'));\n console.log('Run \"stackmemory linear auth\" to connect');\n return;\n }\n\n const client = apiKey\n ? new LinearClient({ apiKey })\n : new LinearClient({\n apiKey: tokens!.accessToken,\n useBearer: true,\n onUnauthorized: async () => {\n const refreshed = await authManager.refreshAccessToken();\n return refreshed.accessToken;\n },\n });\n\n const user = await client.getViewer();\n\n if (user) {\n console.log(chalk.green('\u2713 Connected to Linear'));\n console.log(chalk.cyan(` User: ${user.name} (${user.email})`));\n\n // Show teams\n const teams = await client.getTeams();\n if (teams && teams.length > 0) {\n console.log(chalk.cyan('\\n\uD83D\uDCCB Teams:'));\n teams.forEach((team) => {\n console.log(` - ${team.name} (${team.key})`);\n });\n }\n } else {\n console.log(chalk.red('\u274C Could not connect to Linear'));\n }\n } catch (error: unknown) {\n console.error(\n chalk.red('Status check failed:'),\n (error as Error).message\n );\n }\n });\n\n // List tasks command\n linear\n .command('tasks')\n .description('List Linear tasks')\n .option('--limit <n>', 'Number of tasks to show', '50')\n .option(\n '--status <status>',\n 'Filter by status (backlog, started, completed, etc.)'\n )\n .option('--my', 'Show only tasks assigned to me')\n .option('--cache', 'Show cache stats')\n .option('--refresh', 'Force refresh cache')\n .action(async (options) => {\n try {\n const apiKey = process.env['LINEAR_API_KEY'];\n if (!apiKey) {\n console.log(\n chalk.yellow('\u26A0 Set LINEAR_API_KEY environment variable')\n );\n return;\n }\n\n const restClient = new LinearRestClient(apiKey);\n\n // Show cache stats if requested\n if (options.cache) {\n const stats = restClient.getCacheStats();\n console.log(chalk.cyan('\uD83D\uDCCA Cache Stats:'));\n console.log(` Size: ${stats.size} tasks`);\n console.log(` Age: ${Math.round(stats.age / 1000)}s`);\n console.log(` Fresh: ${stats.fresh ? 'yes' : 'no'}`);\n console.log(\n ` Last sync: ${new Date(stats.lastSync).toLocaleString()}`\n );\n return;\n }\n\n let tasks;\n if (options.my) {\n tasks = await restClient.getMyTasks();\n } else if (options.status) {\n tasks = await restClient.getTasksByStatus(options.status);\n } else {\n tasks = await restClient.getAllTasks(options.refresh);\n }\n\n if (!tasks || tasks.length === 0) {\n console.log(chalk.gray('No tasks found'));\n return;\n }\n\n // Limit results\n const limit = parseInt(options.limit);\n const displayTasks = tasks.slice(0, limit);\n\n const table = new Table({\n head: ['ID', 'Title', 'State', 'Priority', 'Assignee'],\n style: { head: ['cyan'] },\n });\n\n displayTasks.forEach((task) => {\n table.push([\n task.identifier,\n task.title.substring(0, 40) + (task.title.length > 40 ? '...' : ''),\n task.state?.name || '-',\n task.priority ? `P${task.priority}` : '-',\n task.assignee?.name || '-',\n ]);\n });\n\n console.log(table.toString());\n\n // Show counts by status\n const counts = await restClient.getTaskCounts();\n console.log(chalk.cyan('\\n\uD83D\uDCCA Task Summary:'));\n Object.entries(counts).forEach(([status, count]) => {\n console.log(` ${status}: ${count}`);\n });\n\n console.log(\n chalk.gray(\n `\\nShowing ${displayTasks.length} of ${tasks.length} total tasks`\n )\n );\n\n const cacheStats = restClient.getCacheStats();\n console.log(\n chalk.gray(\n `Cache: ${cacheStats.size} tasks, age: ${Math.round(cacheStats.age / 1000)}s`\n )\n );\n } catch (error: unknown) {\n console.error(\n chalk.red('Failed to list tasks:'),\n (error as Error).message\n );\n }\n });\n\n // Update command - update Linear task status\n linear\n .command('update <issueId>')\n .description('Update Linear task status')\n .option(\n '-s, --status <status>',\n 'New status (todo, in-progress, done, canceled)'\n )\n .option('-t, --title <title>', 'Update task title')\n .option('-d, --description <desc>', 'Update task description')\n .option(\n '-p, --priority <priority>',\n 'Set priority (1=urgent, 2=high, 3=medium, 4=low)'\n )\n .action(async (issueId, options) => {\n try {\n const authManager = new LinearAuthManager(process.cwd());\n const tokens = authManager.loadTokens();\n\n if (!tokens) {\n console.error(\n chalk.red('Not authenticated. Run: stackmemory linear auth')\n );\n return;\n }\n\n const client = new LinearClient({\n apiKey: tokens.accessToken,\n });\n\n // Find the issue first\n let issue = await client.getIssue(issueId);\n if (!issue) {\n // Try finding by identifier\n issue = await client.findIssueByIdentifier(issueId);\n }\n\n if (!issue) {\n console.error(chalk.red(`Issue ${issueId} not found`));\n return;\n }\n\n const updates: any = {};\n\n // Handle status update\n if (options.status) {\n const team = await client.getTeam();\n const states = await client.getWorkflowStates(team.id);\n\n const statusMap: Record<string, string> = {\n todo: 'unstarted',\n 'in-progress': 'started',\n done: 'completed',\n canceled: 'cancelled',\n };\n\n const targetType =\n statusMap[options.status.toLowerCase()] || options.status;\n const targetState = states.find((s) => s.type === targetType);\n\n if (!targetState) {\n console.error(chalk.red(`Invalid status: ${options.status}`));\n console.log(chalk.gray('Available states:'));\n states.forEach((s) =>\n console.log(chalk.gray(` - ${s.name} (${s.type})`))\n );\n return;\n }\n\n updates.stateId = targetState.id;\n }\n\n if (options.title) updates.title = options.title;\n if (options.description) updates.description = options.description;\n if (options.priority) updates.priority = parseInt(options.priority);\n\n // Perform update\n const updatedIssue = await client.updateIssue(issue.id, updates);\n\n console.log(\n chalk.green(\n `\u2713 Updated ${updatedIssue.identifier}: ${updatedIssue.title}`\n )\n );\n if (options.status) {\n console.log(chalk.cyan(` Status: ${updatedIssue.state.name}`));\n }\n console.log(chalk.gray(` ${updatedIssue.url}`));\n } catch (error: unknown) {\n console.error(\n chalk.red('Failed to update task:'),\n (error as Error).message\n );\n }\n });\n\n // Config command\n linear\n .command('config')\n .description('Configure Linear sync settings')\n .option('--team <id>', 'Set default team ID')\n .option('--interval <minutes>', 'Auto-sync interval in minutes')\n .option('--direction <dir>', 'Sync direction')\n .option('--conflict <strategy>', 'Conflict resolution strategy')\n .action(async (options) => {\n try {\n const configManager = new LinearConfigManager(process.cwd());\n const config =\n configManager.loadConfig() || configManager.getDefaultConfig();\n\n let updated = false;\n\n if (options.team) {\n // Team ID would need to be stored separately or in a different config\n logger.info('Team ID configuration not yet implemented', {\n teamId: options.team,\n });\n }\n\n if (options.interval) {\n config.interval = parseInt(options.interval);\n updated = true;\n }\n\n if (options.direction) {\n config.direction = options.direction;\n updated = true;\n }\n\n if (options.conflict) {\n config.conflictResolution = options.conflict;\n updated = true;\n }\n\n if (updated) {\n configManager.saveConfig(config);\n console.log(chalk.green('\u2713 Configuration updated'));\n }\n\n // Display current config\n console.log(chalk.cyan('\\n\uD83D\uDCCB Current Configuration:'));\n console.log(` Enabled: ${config.enabled ? 'yes' : 'no'}`);\n console.log(` Interval: ${config.interval} minutes`);\n console.log(` Direction: ${config.direction}`);\n console.log(` Conflicts: ${config.conflictResolution}`);\n } catch (error: unknown) {\n console.error(chalk.red('Config failed:'), (error as Error).message);\n }\n });\n}\n"],
5
+ "mappings": ";;;;AAKA,OAAO,WAAW;AAClB,SAAS,yBAAyB;AAClC,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,OAAO,cAAc;AACrB,SAAS,YAAY;AACrB,SAAS,kBAAkB;AAC3B,SAAS,cAAc;AACvB,OAAO,WAAW;AAQlB,SAAS,kBAAkB,QAAoB;AAC7C,MAAI,OAAO,SAAS;AAClB,YAAQ,IAAI,MAAM,MAAM,oCAA+B,CAAC;AAAA,EAC1D,OAAO;AACL,YAAQ,IAAI,MAAM,OAAO,mCAA8B,CAAC;AAAA,EAC1D;AAEA,MACE,OAAO,OAAO,WAAW,KACzB,OAAO,OAAO,aAAa,KAC3B,OAAO,OAAO,UAAU,GACxB;AACA,YAAQ,IAAI,MAAM,KAAK,sBAAe,CAAC;AACvC,QAAI,OAAO,OAAO,WAAW,GAAG;AAC9B,cAAQ,IAAI,sBAAiB,OAAO,OAAO,QAAQ,QAAQ;AAAA,IAC7D;AACA,QAAI,OAAO,OAAO,aAAa,GAAG;AAChC,cAAQ,IAAI,sBAAiB,OAAO,OAAO,UAAU,QAAQ;AAAA,IAC/D;AACA,QAAI,OAAO,OAAO,UAAU,GAAG;AAC7B,cAAQ,IAAI,uBAAkB,OAAO,OAAO,OAAO,QAAQ;AAAA,IAC7D;AAAA,EACF;AAEA,MAAI,OAAO,UAAU,SAAS,GAAG;AAC/B,YAAQ,IAAI,MAAM,OAAO,uBAAkB,OAAO,UAAU,MAAM,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BAAU;AAAA,MACZ;AAEA,UAAI,SAAS;AACX,sBAAc,WAAW,MAAM;AAC/B,gBAAQ,IAAI,MAAM,MAAM,8BAAyB,CAAC;AAAA,MACpD;AAGA,cAAQ,IAAI,MAAM,KAAK,oCAA6B,CAAC;AACrD,cAAQ,IAAI,cAAc,OAAO,UAAU,QAAQ,IAAI,EAAE;AACzD,cAAQ,IAAI,eAAe,OAAO,QAAQ,UAAU;AACpD,cAAQ,IAAI,gBAAgB,OAAO,SAAS,EAAE;AAC9C,cAAQ,IAAI,gBAAgB,OAAO,kBAAkB,EAAE;AAAA,IACzD,SAAS,OAAgB;AACvB,cAAQ,MAAM,MAAM,IAAI,gBAAgB,GAAI,MAAgB,OAAO;AAAA,IACrE;AAAA,EACF,CAAC;AACL;",
6
6
  "names": []
7
7
  }
@@ -8,6 +8,7 @@ import { homedir } from "os";
8
8
  import { join } from "path";
9
9
  import { existsSync, mkdirSync, writeFileSync, readFileSync } from "fs";
10
10
  import open from "open";
11
+ import { IntegrationError, ErrorCode } from "../../core/errors/index.js";
11
12
  function registerLoginCommand(program) {
12
13
  program.command("login").description("Login to hosted StackMemory service").option("--api-url <url>", "Custom API URL", "https://api.stackmemory.ai").option("--email <email>", "Email address for login").option("--password <password>", "Password (not recommended in CLI)").action(async (options) => {
13
14
  const cfgDir = join(homedir(), ".stackmemory");
@@ -50,7 +51,9 @@ function registerLoginCommand(program) {
50
51
  const data = await response.json();
51
52
  if (!response.ok || !data.success) {
52
53
  if (response.status === 404) {
53
- console.log(chalk.yellow("\n\u26A0\uFE0F Hosted API not available. Would you like to:"));
54
+ console.log(
55
+ chalk.yellow("\n\u26A0\uFE0F Hosted API not available. Would you like to:")
56
+ );
54
57
  const { choice } = await inquirer.prompt([
55
58
  {
56
59
  type: "list",
@@ -80,7 +83,8 @@ function registerLoginCommand(program) {
80
83
  const cfgPath2 = join(cfgDir, "config.json");
81
84
  let cfg2 = {};
82
85
  try {
83
- if (existsSync(cfgPath2)) cfg2 = JSON.parse(readFileSync(cfgPath2, "utf-8"));
86
+ if (existsSync(cfgPath2))
87
+ cfg2 = JSON.parse(readFileSync(cfgPath2, "utf-8"));
84
88
  } catch {
85
89
  }
86
90
  cfg2.database = { mode: "hosted", url: databaseUrl };
@@ -92,7 +96,8 @@ function registerLoginCommand(program) {
92
96
  const cfgPath2 = join(cfgDir, "config.json");
93
97
  let cfg2 = {};
94
98
  try {
95
- if (existsSync(cfgPath2)) cfg2 = JSON.parse(readFileSync(cfgPath2, "utf-8"));
99
+ if (existsSync(cfgPath2))
100
+ cfg2 = JSON.parse(readFileSync(cfgPath2, "utf-8"));
96
101
  } catch {
97
102
  }
98
103
  cfg2.database = { mode: "local" };
@@ -104,12 +109,17 @@ function registerLoginCommand(program) {
104
109
  return;
105
110
  }
106
111
  }
107
- throw new Error(data.error || "Authentication failed");
112
+ throw new IntegrationError(
113
+ data.error || "Authentication failed",
114
+ ErrorCode.LINEAR_AUTH_FAILED,
115
+ { email: credentials.email, apiUrl }
116
+ );
108
117
  }
109
118
  const cfgPath = join(cfgDir, "config.json");
110
119
  let cfg = {};
111
120
  try {
112
- if (existsSync(cfgPath)) cfg = JSON.parse(readFileSync(cfgPath, "utf-8"));
121
+ if (existsSync(cfgPath))
122
+ cfg = JSON.parse(readFileSync(cfgPath, "utf-8"));
113
123
  } catch {
114
124
  }
115
125
  cfg.auth = {
@@ -132,14 +142,26 @@ ${data.databaseUrl ? `DATABASE_URL=${data.databaseUrl}` : ""}
132
142
  `;
133
143
  writeFileSync(envFile, envContent);
134
144
  console.log(chalk.green("\n\u2705 Successfully logged in to StackMemory"));
135
- console.log(chalk.green(`\u2713 Configuration saved to ~/.stackmemory/config.json`));
145
+ console.log(
146
+ chalk.green(`\u2713 Configuration saved to ~/.stackmemory/config.json`)
147
+ );
136
148
  console.log(chalk.gray("\nYou can now use:"));
137
- console.log(chalk.cyan(" stackmemory sync ") + chalk.gray("- Sync your context to the cloud"));
138
- console.log(chalk.cyan(" stackmemory db status") + chalk.gray("- Check database connection"));
139
- console.log(chalk.cyan(" stackmemory context ") + chalk.gray("- Manage your contexts"));
149
+ console.log(
150
+ chalk.cyan(" stackmemory sync ") + chalk.gray("- Sync your context to the cloud")
151
+ );
152
+ console.log(
153
+ chalk.cyan(" stackmemory db status") + chalk.gray("- Check database connection")
154
+ );
155
+ console.log(
156
+ chalk.cyan(" stackmemory context ") + chalk.gray("- Manage your contexts")
157
+ );
140
158
  } catch (error) {
141
159
  console.error(chalk.red("\n\u274C Login failed:"), error.message);
142
- console.log(chalk.yellow("\nTip: Visit https://stackmemory.ai/signup to create an account"));
160
+ console.log(
161
+ chalk.yellow(
162
+ "\nTip: Visit https://stackmemory.ai/signup to create an account"
163
+ )
164
+ );
143
165
  process.exit(1);
144
166
  }
145
167
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/cli/commands/login.ts"],
4
- "sourcesContent": ["import { Command } from 'commander';\nimport inquirer from 'inquirer';\nimport chalk from 'chalk';\nimport { homedir } from 'os';\nimport { join } from 'path';\nimport { existsSync, mkdirSync, writeFileSync, readFileSync } from 'fs';\nimport open from 'open';\n\ninterface ConfigShape {\n version?: string;\n setupCompleted?: string;\n features?: any;\n paths?: any;\n database?: { mode?: 'local' | 'hosted'; url?: string };\n auth?: { \n apiKey?: string;\n apiUrl?: string;\n email?: string;\n };\n}\n\ninterface AuthResponse {\n success: boolean;\n apiKey?: string;\n databaseUrl?: string;\n email?: string;\n error?: string;\n}\n\nexport function registerLoginCommand(program: Command): void {\n program\n .command('login')\n .description('Login to hosted StackMemory service')\n .option('--api-url <url>', 'Custom API URL', 'https://api.stackmemory.ai')\n .option('--email <email>', 'Email address for login')\n .option('--password <password>', 'Password (not recommended in CLI)')\n .action(async (options) => {\n const cfgDir = join(homedir(), '.stackmemory');\n if (!existsSync(cfgDir)) mkdirSync(cfgDir, { recursive: true });\n\n console.log(chalk.cyan('\uD83D\uDD10 StackMemory Hosted Service Login\\n'));\n\n // Prompt for credentials\n const credentials = await inquirer.prompt([\n {\n type: 'input',\n name: 'email',\n message: 'Email:',\n default: options.email,\n validate: (input: string) => {\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return emailRegex.test(input) ? true : 'Please enter a valid email';\n },\n },\n {\n type: 'password',\n name: 'password',\n message: 'Password:',\n default: options.password,\n mask: '*',\n validate: (input: string) => input.length >= 6 ? true : 'Password must be at least 6 characters',\n },\n ]);\n\n console.log(chalk.gray('\\nAuthenticating with StackMemory API...'));\n\n try {\n // Authenticate with the hosted API\n const apiUrl = options.apiUrl || process.env.STACKMEMORY_API_URL || 'https://api.stackmemory.ai';\n const response = await fetch(`${apiUrl}/auth/login`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'StackMemory-CLI/0.3.19',\n },\n body: JSON.stringify({\n email: credentials.email,\n password: credentials.password,\n }),\n });\n\n const data: AuthResponse = await response.json();\n\n if (!response.ok || !data.success) {\n if (response.status === 404) {\n // Fallback to Railway server if hosted API not available\n console.log(chalk.yellow('\\n\u26A0\uFE0F Hosted API not available. Would you like to:'));\n const { choice } = await inquirer.prompt([\n {\n type: 'list',\n name: 'choice',\n message: 'Select an option:',\n choices: [\n { name: 'Open signup page in browser', value: 'signup' },\n { name: 'Configure database URL manually', value: 'manual' },\n { name: 'Use local database', value: 'local' },\n { name: 'Cancel', value: 'cancel' },\n ],\n },\n ]);\n\n if (choice === 'signup') {\n await open('https://stackmemory.ai/signup');\n console.log(chalk.cyan('Opening signup page in browser...'));\n return;\n } else if (choice === 'manual') {\n const { databaseUrl } = await inquirer.prompt([\n {\n type: 'password',\n name: 'databaseUrl',\n message: 'Enter your DATABASE_URL (postgres://...):',\n validate: (input: string) =>\n input.startsWith('postgres://') || input.startsWith('postgresql://')\n ? true\n : 'Must start with postgres:// or postgresql://',\n },\n ]);\n\n // Save manual configuration\n const cfgPath = join(cfgDir, 'config.json');\n let cfg: ConfigShape = {};\n try {\n if (existsSync(cfgPath)) cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));\n } catch {}\n \n cfg.database = { mode: 'hosted', url: databaseUrl };\n cfg.auth = { email: credentials.email };\n \n writeFileSync(cfgPath, JSON.stringify(cfg, null, 2));\n console.log(chalk.green('\u2713 Database configured successfully'));\n return;\n } else if (choice === 'local') {\n const cfgPath = join(cfgDir, 'config.json');\n let cfg: ConfigShape = {};\n try {\n if (existsSync(cfgPath)) cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));\n } catch {}\n \n cfg.database = { mode: 'local' };\n writeFileSync(cfgPath, JSON.stringify(cfg, null, 2));\n console.log(chalk.green('\u2713 Switched to local database mode'));\n return;\n } else {\n console.log(chalk.gray('Login cancelled'));\n return;\n }\n }\n\n throw new Error(data.error || 'Authentication failed');\n }\n\n // Save configuration\n const cfgPath = join(cfgDir, 'config.json');\n let cfg: ConfigShape = {};\n try {\n if (existsSync(cfgPath)) cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));\n } catch {}\n\n cfg.auth = {\n apiKey: data.apiKey,\n apiUrl: apiUrl,\n email: credentials.email,\n };\n\n if (data.databaseUrl) {\n cfg.database = {\n mode: 'hosted',\n url: data.databaseUrl,\n };\n }\n\n writeFileSync(cfgPath, JSON.stringify(cfg, null, 2));\n \n // Save environment variables\n const envFile = join(cfgDir, 'stackmemory.env');\n const envContent = `# StackMemory Authentication\nSTACKMEMORY_API_KEY=${data.apiKey}\nSTACKMEMORY_API_URL=${apiUrl}\n${data.databaseUrl ? `DATABASE_URL=${data.databaseUrl}` : ''}\n`;\n writeFileSync(envFile, envContent);\n\n console.log(chalk.green('\\n\u2705 Successfully logged in to StackMemory'));\n console.log(chalk.green(`\u2713 Configuration saved to ~/.stackmemory/config.json`));\n console.log(chalk.gray('\\nYou can now use:'));\n console.log(chalk.cyan(' stackmemory sync ') + chalk.gray('- Sync your context to the cloud'));\n console.log(chalk.cyan(' stackmemory db status') + chalk.gray('- Check database connection'));\n console.log(chalk.cyan(' stackmemory context ') + chalk.gray('- Manage your contexts'));\n \n } catch (error: any) {\n console.error(chalk.red('\\n\u274C Login failed:'), error.message);\n console.log(chalk.yellow('\\nTip: Visit https://stackmemory.ai/signup to create an account'));\n process.exit(1);\n }\n });\n}"],
5
- "mappings": ";;;;AACA,OAAO,cAAc;AACrB,OAAO,WAAW;AAClB,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,YAAY,WAAW,eAAe,oBAAoB;AACnE,OAAO,UAAU;AAuBV,SAAS,qBAAqB,SAAwB;AAC3D,UACG,QAAQ,OAAO,EACf,YAAY,qCAAqC,EACjD,OAAO,mBAAmB,kBAAkB,4BAA4B,EACxE,OAAO,mBAAmB,yBAAyB,EACnD,OAAO,yBAAyB,mCAAmC,EACnE,OAAO,OAAO,YAAY;AACzB,UAAM,SAAS,KAAK,QAAQ,GAAG,cAAc;AAC7C,QAAI,CAAC,WAAW,MAAM,EAAG,WAAU,QAAQ,EAAE,WAAW,KAAK,CAAC;AAE9D,YAAQ,IAAI,MAAM,KAAK,8CAAuC,CAAC;AAG/D,UAAM,cAAc,MAAM,SAAS,OAAO;AAAA,MACxC;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,SAAS;AAAA,QACT,SAAS,QAAQ;AAAA,QACjB,UAAU,CAAC,UAAkB;AAC3B,gBAAM,aAAa;AACnB,iBAAO,WAAW,KAAK,KAAK,IAAI,OAAO;AAAA,QACzC;AAAA,MACF;AAAA,MACA;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,SAAS;AAAA,QACT,SAAS,QAAQ;AAAA,QACjB,MAAM;AAAA,QACN,UAAU,CAAC,UAAkB,MAAM,UAAU,IAAI,OAAO;AAAA,MAC1D;AAAA,IACF,CAAC;AAED,YAAQ,IAAI,MAAM,KAAK,0CAA0C,CAAC;AAElE,QAAI;AAEF,YAAM,SAAS,QAAQ,UAAU,QAAQ,IAAI,uBAAuB;AACpE,YAAM,WAAW,MAAM,MAAM,GA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nD,YAAM,UAAU,KAAK,QAAQ,iBAAiB;AAC9C,YAAM,aAAa;AAAA,sBACL,KAAK,MAAM;AAAA,sBACX,MAAM;AAAA,EAC1B,KAAK,cAAc,gBAAgB,KAAK,WAAW,KAAK,EAAE;AAAA;AAEpD,oBAAc,SAAS,UAAU;AAEjC,cAAQ,IAAI,MAAM,MAAM,gDAA2C,CAAC;AACpE,cAAQ,IAAI,MAAM,MAAM,0DAAqD,CAAC;AAC9E,cAAQ,IAAI,MAAM,KAAK,oBAAoB,CAAC;AAC5C,cAAQ,IAAI,MAAM,KAAK,yBAAyB,IAAI,MAAM,KAAK,kCAAkC,CAAC;AAClG,cAAQ,IAAI,MAAM,KAAK,yBAAyB,IAAI,MAAM,KAAK,6BAA6B,CAAC;AAC7F,cAAQ,IAAI,MAAM,KAAK,yBAAyB,IAAI,MAAM,KAAK,wBAAwB,CAAC;AAAA,IAE1F,SAAS,OAAY;AACnB,cAAQ,MAAM,MAAM,IAAI,wBAAmB,GAAG,MAAM,OAAO;AAC3D,cAAQ,IAAI,MAAM,OAAO,iEAAiE,CAAC;AAC3F,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF,CAAC;AACL;",
4
+ "sourcesContent": ["import { Command } from 'commander';\nimport inquirer from 'inquirer';\nimport chalk from 'chalk';\nimport { homedir } from 'os';\nimport { join } from 'path';\nimport { existsSync, mkdirSync, writeFileSync, readFileSync } from 'fs';\nimport open from 'open';\nimport { IntegrationError, ErrorCode } from '../../core/errors/index.js';\n\ninterface ConfigShape {\n version?: string;\n setupCompleted?: string;\n features?: any;\n paths?: any;\n database?: { mode?: 'local' | 'hosted'; url?: string };\n auth?: {\n apiKey?: string;\n apiUrl?: string;\n email?: string;\n };\n}\n\ninterface AuthResponse {\n success: boolean;\n apiKey?: string;\n databaseUrl?: string;\n email?: string;\n error?: string;\n}\n\nexport function registerLoginCommand(program: Command): void {\n program\n .command('login')\n .description('Login to hosted StackMemory service')\n .option('--api-url <url>', 'Custom API URL', 'https://api.stackmemory.ai')\n .option('--email <email>', 'Email address for login')\n .option('--password <password>', 'Password (not recommended in CLI)')\n .action(async (options) => {\n const cfgDir = join(homedir(), '.stackmemory');\n if (!existsSync(cfgDir)) mkdirSync(cfgDir, { recursive: true });\n\n console.log(chalk.cyan('\uD83D\uDD10 StackMemory Hosted Service Login\\n'));\n\n // Prompt for credentials\n const credentials = await inquirer.prompt([\n {\n type: 'input',\n name: 'email',\n message: 'Email:',\n default: options.email,\n validate: (input: string) => {\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return emailRegex.test(input) ? true : 'Please enter a valid email';\n },\n },\n {\n type: 'password',\n name: 'password',\n message: 'Password:',\n default: options.password,\n mask: '*',\n validate: (input: string) =>\n input.length >= 6 ? true : 'Password must be at least 6 characters',\n },\n ]);\n\n console.log(chalk.gray('\\nAuthenticating with StackMemory API...'));\n\n try {\n // Authenticate with the hosted API\n const apiUrl =\n options.apiUrl ||\n process.env.STACKMEMORY_API_URL ||\n 'https://api.stackmemory.ai';\n const response = await fetch(`${apiUrl}/auth/login`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'StackMemory-CLI/0.3.19',\n },\n body: JSON.stringify({\n email: credentials.email,\n password: credentials.password,\n }),\n });\n\n const data: AuthResponse = await response.json();\n\n if (!response.ok || !data.success) {\n if (response.status === 404) {\n // Fallback to Railway server if hosted API not available\n console.log(\n chalk.yellow('\\n\u26A0\uFE0F Hosted API not available. Would you like to:')\n );\n const { choice } = await inquirer.prompt([\n {\n type: 'list',\n name: 'choice',\n message: 'Select an option:',\n choices: [\n { name: 'Open signup page in browser', value: 'signup' },\n { name: 'Configure database URL manually', value: 'manual' },\n { name: 'Use local database', value: 'local' },\n { name: 'Cancel', value: 'cancel' },\n ],\n },\n ]);\n\n if (choice === 'signup') {\n await open('https://stackmemory.ai/signup');\n console.log(chalk.cyan('Opening signup page in browser...'));\n return;\n } else if (choice === 'manual') {\n const { databaseUrl } = await inquirer.prompt([\n {\n type: 'password',\n name: 'databaseUrl',\n message: 'Enter your DATABASE_URL (postgres://...):',\n validate: (input: string) =>\n input.startsWith('postgres://') ||\n input.startsWith('postgresql://')\n ? true\n : 'Must start with postgres:// or postgresql://',\n },\n ]);\n\n // Save manual configuration\n const cfgPath = join(cfgDir, 'config.json');\n let cfg: ConfigShape = {};\n try {\n if (existsSync(cfgPath))\n cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));\n } catch {}\n\n cfg.database = { mode: 'hosted', url: databaseUrl };\n cfg.auth = { email: credentials.email };\n\n writeFileSync(cfgPath, JSON.stringify(cfg, null, 2));\n console.log(chalk.green('\u2713 Database configured successfully'));\n return;\n } else if (choice === 'local') {\n const cfgPath = join(cfgDir, 'config.json');\n let cfg: ConfigShape = {};\n try {\n if (existsSync(cfgPath))\n cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));\n } catch {}\n\n cfg.database = { mode: 'local' };\n writeFileSync(cfgPath, JSON.stringify(cfg, null, 2));\n console.log(chalk.green('\u2713 Switched to local database mode'));\n return;\n } else {\n console.log(chalk.gray('Login cancelled'));\n return;\n }\n }\n\n throw new IntegrationError(\n data.error || 'Authentication failed',\n ErrorCode.LINEAR_AUTH_FAILED,\n { email: credentials.email, apiUrl }\n );\n }\n\n // Save configuration\n const cfgPath = join(cfgDir, 'config.json');\n let cfg: ConfigShape = {};\n try {\n if (existsSync(cfgPath))\n cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));\n } catch {}\n\n cfg.auth = {\n apiKey: data.apiKey,\n apiUrl: apiUrl,\n email: credentials.email,\n };\n\n if (data.databaseUrl) {\n cfg.database = {\n mode: 'hosted',\n url: data.databaseUrl,\n };\n }\n\n writeFileSync(cfgPath, JSON.stringify(cfg, null, 2));\n\n // Save environment variables\n const envFile = join(cfgDir, 'stackmemory.env');\n const envContent = `# StackMemory Authentication\nSTACKMEMORY_API_KEY=${data.apiKey}\nSTACKMEMORY_API_URL=${apiUrl}\n${data.databaseUrl ? `DATABASE_URL=${data.databaseUrl}` : ''}\n`;\n writeFileSync(envFile, envContent);\n\n console.log(chalk.green('\\n\u2705 Successfully logged in to StackMemory'));\n console.log(\n chalk.green(`\u2713 Configuration saved to ~/.stackmemory/config.json`)\n );\n console.log(chalk.gray('\\nYou can now use:'));\n console.log(\n chalk.cyan(' stackmemory sync ') +\n chalk.gray('- Sync your context to the cloud')\n );\n console.log(\n chalk.cyan(' stackmemory db status') +\n chalk.gray('- Check database connection')\n );\n console.log(\n chalk.cyan(' stackmemory context ') +\n chalk.gray('- Manage your contexts')\n );\n } catch (error: any) {\n console.error(chalk.red('\\n\u274C Login failed:'), error.message);\n console.log(\n chalk.yellow(\n '\\nTip: Visit https://stackmemory.ai/signup to create an account'\n )\n );\n process.exit(1);\n }\n });\n}\n"],
5
+ "mappings": ";;;;AACA,OAAO,cAAc;AACrB,OAAO,WAAW;AAClB,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,YAAY,WAAW,eAAe,oBAAoB;AACnE,OAAO,UAAU;AACjB,SAAS,kBAAkB,iBAAiB;AAuBrC,SAAS,qBAAqB,SAAwB;AAC3D,UACG,QAAQ,OAAO,EACf,YAAY,qCAAqC,EACjD,OAAO,mBAAmB,kBAAkB,4BAA4B,EACxE,OAAO,mBAAmB,yBAAyB,EACnD,OAAO,yBAAyB,mCAAmC,EACnE,OAAO,OAAO,YAAY;AACzB,UAAM,SAAS,KAAK,QAAQ,GAAG,cAAc;AAC7C,QAAI,CAAC,WAAW,MAAM,EAAG,WAAU,QAAQ,EAAE,WAAW,KAAK,CAAC;AAE9D,YAAQ,IAAI,MAAM,KAAK,8CAAuC,CAAC;AAG/D,UAAM,cAAc,MAAM,SAAS,OAAO;AAAA,MACxC;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,SAAS;AAAA,QACT,SAAS,QAAQ;AAAA,QACjB,UAAU,CAAC,UAAkB;AAC3B,gBAAM,aAAa;AACnB,iBAAO,WAA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