@stackmemoryai/stackmemory 0.3.8 → 0.3.10
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.
- package/README.md +53 -0
- package/dist/agents/core/agent-task-manager.js +12 -1
- package/dist/agents/core/agent-task-manager.js.map +3 -3
- package/dist/agents/testing-agent.js +610 -0
- package/dist/agents/testing-agent.js.map +7 -0
- package/dist/cli/claude-sm.js +2 -2
- package/dist/cli/claude-sm.js.map +2 -2
- package/dist/cli/codex-sm.js +2 -2
- package/dist/cli/codex-sm.js.map +2 -2
- package/dist/cli/commands/handoff.js +65 -18
- package/dist/cli/commands/handoff.js.map +3 -3
- package/dist/cli/commands/onboard.js +3 -3
- package/dist/cli/commands/onboard.js.map +2 -2
- package/dist/cli/commands/quality.js +2 -2
- package/dist/cli/commands/quality.js.map +2 -2
- package/dist/cli/commands/skills.js +113 -28
- package/dist/cli/commands/skills.js.map +2 -2
- package/dist/cli/commands/test.js +282 -0
- package/dist/cli/commands/test.js.map +7 -0
- package/dist/cli/commands/worktree.js +28 -10
- package/dist/cli/commands/worktree.js.map +2 -2
- package/dist/cli/index.js +2 -0
- package/dist/cli/index.js.map +2 -2
- package/dist/core/config/config-manager.js +26 -0
- package/dist/core/config/config-manager.js.map +3 -3
- package/dist/core/context/frame-manager.js +139 -0
- package/dist/core/context/frame-manager.js.map +2 -2
- package/dist/core/context/recursive-context-manager.js +582 -0
- package/dist/core/context/recursive-context-manager.js.map +7 -0
- package/dist/core/context/refactored-frame-manager.js +180 -1
- package/dist/core/context/refactored-frame-manager.js.map +2 -2
- package/dist/core/execution/parallel-executor.js +254 -0
- package/dist/core/execution/parallel-executor.js.map +7 -0
- package/dist/core/utils/update-checker.js +2 -2
- package/dist/core/utils/update-checker.js.map +2 -2
- package/dist/integrations/anthropic/client.js +259 -0
- package/dist/integrations/anthropic/client.js.map +7 -0
- package/dist/integrations/claude-code/subagent-client-stub.js +16 -0
- package/dist/integrations/claude-code/subagent-client-stub.js.map +7 -0
- package/dist/integrations/claude-code/subagent-client.js +404 -0
- package/dist/integrations/claude-code/subagent-client.js.map +7 -0
- package/dist/skills/claude-skills.js +191 -0
- package/dist/skills/claude-skills.js.map +2 -2
- package/dist/skills/recursive-agent-orchestrator.js +559 -0
- package/dist/skills/recursive-agent-orchestrator.js.map +7 -0
- package/dist/skills/security-secrets-scanner.js +280 -0
- package/dist/skills/security-secrets-scanner.js.map +7 -0
- package/dist/skills/unified-rlm-orchestrator.js +400 -0
- package/dist/skills/unified-rlm-orchestrator.js.map +7 -0
- package/package.json +3 -2
package/dist/cli/claude-sm.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { spawn, execSync } from "child_process";
|
|
2
|
+
import { spawn, execSync, execFileSync } from "child_process";
|
|
3
3
|
import * as fs from "fs";
|
|
4
4
|
import * as path from "path";
|
|
5
5
|
import * as os from "os";
|
|
@@ -46,7 +46,7 @@ class ClaudeSM {
|
|
|
46
46
|
];
|
|
47
47
|
for (const smPath of possiblePaths) {
|
|
48
48
|
try {
|
|
49
|
-
|
|
49
|
+
execFileSync("which", [smPath], { stdio: "ignore" });
|
|
50
50
|
return smPath;
|
|
51
51
|
} catch {
|
|
52
52
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/cli/claude-sm.ts"],
|
|
4
|
-
"sourcesContent": ["#!/usr/bin/env node\n\n/**\n * claude-sm: Claude wrapper with StackMemory and worktree integration\n * Automatically manages context persistence and instance isolation\n */\n\nimport { spawn, execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { program } from 'commander';\nimport { v4 as uuidv4 } from 'uuid';\nimport chalk from 'chalk';\nimport { initializeTracing, trace } from '../core/trace/index.js';\n\ninterface ClaudeConfig {\n instanceId: string;\n worktreePath?: string;\n useSandbox: boolean;\n useChrome: boolean;\n useWorktree: boolean;\n contextEnabled: boolean;\n branch?: string;\n task?: string;\n tracingEnabled: boolean;\n verboseTracing: boolean;\n}\n\nclass ClaudeSM {\n private config: ClaudeConfig;\n private stackmemoryPath: string;\n private worktreeScriptPath: string;\n private claudeConfigDir: string;\n\n constructor() {\n this.config = {\n instanceId: this.generateInstanceId(),\n useSandbox: false,\n useChrome: false,\n useWorktree: false,\n contextEnabled: true,\n tracingEnabled: true, // Enable tracing by default for claude-sm\n verboseTracing: false,\n };\n\n this.stackmemoryPath = this.findStackMemory();\n this.worktreeScriptPath = path.join(\n __dirname,\n '../../scripts/claude-worktree-manager.sh'\n );\n this.claudeConfigDir = path.join(os.homedir(), '.claude');\n\n // Ensure config directory exists\n if (!fs.existsSync(this.claudeConfigDir)) {\n fs.mkdirSync(this.claudeConfigDir, { recursive: true });\n }\n }\n\n private generateInstanceId(): string {\n return uuidv4().substring(0, 8);\n }\n\n private findStackMemory(): string {\n // Check multiple possible locations\n const possiblePaths = [\n path.join(os.homedir(), '.stackmemory', 'bin', 'stackmemory'),\n '/usr/local/bin/stackmemory',\n '/opt/homebrew/bin/stackmemory',\n 'stackmemory', // Rely on PATH\n ];\n\n for (const smPath of possiblePaths) {\n try {\n execSync(`which ${smPath}`, { stdio: 'ignore' });\n return smPath;\n } catch {\n // Continue searching\n }\n }\n\n return 'stackmemory'; // Fallback to PATH\n }\n\n private isGitRepo(): boolean {\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n }\n\n private getCurrentBranch(): string {\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n encoding: 'utf8',\n }).trim();\n } catch {\n return 'main';\n }\n }\n\n private hasUncommittedChanges(): boolean {\n try {\n const status = execSync('git status --porcelain', { encoding: 'utf8' });\n return status.length > 0;\n } catch {\n return false;\n }\n }\n\n private setupWorktree(): string | null {\n if (!this.config.useWorktree || !this.isGitRepo()) {\n return null;\n }\n\n console.log(chalk.blue('\uD83C\uDF33 Setting up isolated worktree...'));\n\n const timestamp = new Date()\n .toISOString()\n .replace(/[:.]/g, '-')\n .substring(0, 19);\n const branch =\n this.config.branch ||\n `claude-${this.config.task || 'work'}-${timestamp}-${this.config.instanceId}`;\n const repoName = path.basename(process.cwd());\n const worktreePath = path.join(\n path.dirname(process.cwd()),\n `${repoName}--${branch}`\n );\n\n try {\n // Create worktree\n const flags = [];\n if (this.config.useSandbox) flags.push('--sandbox');\n if (this.config.useChrome) flags.push('--chrome');\n\n const cmd = `git worktree add -b \"${branch}\" \"${worktreePath}\"`;\n execSync(cmd, { stdio: 'inherit' });\n\n console.log(chalk.green(`\u2705 Worktree created: ${worktreePath}`));\n console.log(chalk.gray(` Branch: ${branch}`));\n\n // Save worktree config\n const configPath = path.join(worktreePath, '.claude-instance.json');\n const configData = {\n instanceId: this.config.instanceId,\n worktreePath,\n branch,\n task: this.config.task,\n sandboxEnabled: this.config.useSandbox,\n chromeEnabled: this.config.useChrome,\n created: new Date().toISOString(),\n parentRepo: process.cwd(),\n };\n fs.writeFileSync(configPath, JSON.stringify(configData, null, 2));\n\n // Copy environment files\n const envFiles = ['.env', '.env.local', '.mise.toml', '.tool-versions'];\n for (const file of envFiles) {\n const srcPath = path.join(process.cwd(), file);\n if (fs.existsSync(srcPath)) {\n fs.copyFileSync(srcPath, path.join(worktreePath, file));\n }\n }\n\n return worktreePath;\n } catch (err: unknown) {\n console.error(chalk.red('\u274C Failed to create worktree:'), err);\n return null;\n }\n }\n\n private saveContext(\n message: string,\n metadata: Record<string, unknown> = {}\n ): void {\n if (!this.config.contextEnabled) return;\n\n try {\n const contextData = {\n message,\n metadata: {\n ...metadata,\n instanceId: this.config.instanceId,\n worktree: this.config.worktreePath,\n timestamp: new Date().toISOString(),\n },\n };\n\n const cmd = `${this.stackmemoryPath} context save --json '${JSON.stringify(contextData)}'`;\n execSync(cmd, { stdio: 'ignore' });\n } catch {\n // Silently fail - don't interrupt Claude\n }\n }\n\n private loadContext(): void {\n if (!this.config.contextEnabled) return;\n\n try {\n console.log(chalk.blue('\uD83D\uDCDA Loading previous context...'));\n\n const cmd = `${this.stackmemoryPath} context list --limit 5 --format json`;\n const output = execSync(cmd, { encoding: 'utf8' });\n const contexts = JSON.parse(output);\n\n if (contexts.length > 0) {\n console.log(chalk.gray('Recent context loaded:'));\n contexts.forEach(\n (ctx: { message: string; metadata?: { timestamp?: string } }) => {\n console.log(\n chalk.gray(` - ${ctx.message} (${ctx.metadata?.timestamp})`)\n );\n }\n );\n }\n } catch {\n // Silently continue\n }\n }\n\n private detectMultipleInstances(): boolean {\n try {\n const lockDir = path.join(process.cwd(), '.claude-worktree-locks');\n if (!fs.existsSync(lockDir)) return false;\n\n const locks = fs.readdirSync(lockDir).filter((f) => f.endsWith('.lock'));\n const activeLocks = locks.filter((lockFile) => {\n const lockPath = path.join(lockDir, lockFile);\n const lockData = JSON.parse(fs.readFileSync(lockPath, 'utf8'));\n const lockAge = Date.now() - new Date(lockData.created).getTime();\n return lockAge < 24 * 60 * 60 * 1000; // Less than 24 hours old\n });\n\n return activeLocks.length > 0;\n } catch {\n return false;\n }\n }\n\n private suggestWorktreeMode(): void {\n if (this.hasUncommittedChanges()) {\n console.log(chalk.yellow('\u26A0\uFE0F Uncommitted changes detected'));\n console.log(\n chalk.gray(' Consider using --worktree to work in isolation')\n );\n }\n\n if (this.detectMultipleInstances()) {\n console.log(chalk.yellow('\u26A0\uFE0F Other Claude instances detected'));\n console.log(\n chalk.gray(' Using --worktree is recommended to avoid conflicts')\n );\n }\n }\n\n public async run(args: string[]): Promise<void> {\n // Parse arguments\n const claudeArgs: string[] = [];\n let i = 0;\n\n while (i < args.length) {\n const arg = args[i];\n\n switch (arg) {\n case '--worktree':\n case '-w':\n this.config.useWorktree = true;\n break;\n case '--sandbox':\n case '-s':\n this.config.useSandbox = true;\n claudeArgs.push('--sandbox');\n break;\n case '--chrome':\n case '-c':\n this.config.useChrome = true;\n claudeArgs.push('--chrome');\n break;\n case '--no-context':\n this.config.contextEnabled = false;\n break;\n case '--no-trace':\n this.config.tracingEnabled = false;\n break;\n case '--verbose-trace':\n this.config.verboseTracing = true;\n break;\n case '--branch':\n case '-b':\n i++;\n this.config.branch = args[i];\n break;\n case '--task':\n case '-t':\n i++;\n this.config.task = args[i];\n break;\n case '--auto':\n case '-a':\n // Auto mode: detect and apply best settings\n if (this.isGitRepo()) {\n this.config.useWorktree =\n this.hasUncommittedChanges() || this.detectMultipleInstances();\n }\n break;\n default:\n claudeArgs.push(arg);\n }\n i++;\n }\n\n // Initialize tracing system if enabled\n if (this.config.tracingEnabled) {\n // Set up environment for tracing\n process.env['DEBUG_TRACE'] = 'true';\n process.env['STACKMEMORY_DEBUG'] = 'true';\n process.env['TRACE_OUTPUT'] = 'file'; // Write to file to not clutter Claude output\n process.env['TRACE_MASK_SENSITIVE'] = 'true'; // Always mask sensitive data\n\n if (this.config.verboseTracing) {\n process.env['TRACE_VERBOSITY'] = 'full';\n process.env['TRACE_PARAMS'] = 'true';\n process.env['TRACE_RESULTS'] = 'true';\n process.env['TRACE_MEMORY'] = 'true';\n } else {\n process.env['TRACE_VERBOSITY'] = 'summary';\n process.env['TRACE_PARAMS'] = 'true';\n process.env['TRACE_RESULTS'] = 'false';\n }\n\n // Initialize the tracing system\n initializeTracing();\n\n // Start tracing this Claude session\n trace.command(\n 'claude-sm',\n {\n instanceId: this.config.instanceId,\n worktree: this.config.useWorktree,\n sandbox: this.config.useSandbox,\n task: this.config.task,\n },\n async () => {\n // Session tracing will wrap the entire Claude execution\n }\n );\n }\n\n // Show header\n console.log(chalk.blue('\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557'));\n console.log(chalk.blue('\u2551 Claude + StackMemory + Worktree \u2551'));\n console.log(chalk.blue('\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D'));\n console.log();\n\n // Check Git repo status\n if (this.isGitRepo()) {\n const branch = this.getCurrentBranch();\n console.log(chalk.gray(`\uD83D\uDCCD Current branch: ${branch}`));\n\n if (!this.config.useWorktree) {\n this.suggestWorktreeMode();\n }\n }\n\n // Setup worktree if requested\n if (this.config.useWorktree) {\n const worktreePath = this.setupWorktree();\n if (worktreePath) {\n this.config.worktreePath = worktreePath;\n process.chdir(worktreePath);\n\n // Save context about worktree creation\n this.saveContext('Created worktree for Claude instance', {\n action: 'worktree_created',\n path: worktreePath,\n branch: this.config.branch,\n });\n }\n }\n\n // Load previous context\n this.loadContext();\n\n // Setup environment\n process.env['CLAUDE_INSTANCE_ID'] = this.config.instanceId;\n if (this.config.worktreePath) {\n process.env['CLAUDE_WORKTREE_PATH'] = this.config.worktreePath;\n }\n\n console.log(chalk.gray(`\uD83E\uDD16 Instance ID: ${this.config.instanceId}`));\n console.log(chalk.gray(`\uD83D\uDCC1 Working in: ${process.cwd()}`));\n\n if (this.config.useSandbox) {\n console.log(chalk.yellow('\uD83D\uDD12 Sandbox mode enabled'));\n }\n if (this.config.useChrome) {\n console.log(chalk.yellow('\uD83C\uDF10 Chrome automation enabled'));\n }\n if (this.config.tracingEnabled) {\n console.log(\n chalk.gray(`\uD83D\uDD0D Debug tracing enabled (logs to ~/.stackmemory/traces/)`)\n );\n if (this.config.verboseTracing) {\n console.log(\n chalk.gray(` Verbose mode: capturing all execution details`)\n );\n }\n }\n\n console.log();\n console.log(chalk.gray('Starting Claude...'));\n console.log(chalk.gray('\u2500'.repeat(42)));\n\n // Launch Claude\n const claude = spawn('claude', claudeArgs, {\n stdio: 'inherit',\n env: process.env,\n });\n\n // Handle exit\n claude.on('exit', (code) => {\n // Save final context\n this.saveContext('Claude session ended', {\n action: 'session_end',\n exitCode: code,\n });\n\n // End tracing and show summary if enabled\n if (this.config.tracingEnabled) {\n const summary = trace.getExecutionSummary();\n console.log();\n console.log(chalk.gray('\u2500'.repeat(42)));\n console.log(chalk.blue('Debug Trace Summary:'));\n console.log(chalk.gray(summary));\n }\n\n // Offer to clean up worktree\n if (this.config.worktreePath) {\n console.log();\n console.log(chalk.gray('\u2500'.repeat(42)));\n console.log(chalk.blue('Session ended in worktree:'));\n console.log(chalk.gray(` ${this.config.worktreePath}`));\n console.log();\n console.log(chalk.gray('To remove worktree: gd_claude'));\n console.log(chalk.gray('To merge to main: cwm'));\n }\n\n process.exit(code || 0);\n });\n\n // Handle signals\n process.on('SIGINT', () => {\n this.saveContext('Claude session interrupted', {\n action: 'session_interrupt',\n });\n claude.kill('SIGINT');\n });\n\n process.on('SIGTERM', () => {\n this.saveContext('Claude session terminated', {\n action: 'session_terminate',\n });\n claude.kill('SIGTERM');\n });\n }\n}\n\n// CLI interface\nprogram\n .name('claude-sm')\n .description('Claude with StackMemory context and worktree isolation')\n .version('1.0.0')\n .option('-w, --worktree', 'Create isolated worktree for this instance')\n .option('-s, --sandbox', 'Enable sandbox mode (file/network restrictions)')\n .option('-c, --chrome', 'Enable Chrome automation')\n .option('-a, --auto', 'Automatically detect and apply best settings')\n .option('-b, --branch <name>', 'Specify branch name for worktree')\n .option('-t, --task <desc>', 'Task description for context')\n .option('--no-context', 'Disable StackMemory context integration')\n .option('--no-trace', 'Disable debug tracing (enabled by default)')\n .option('--verbose-trace', 'Enable verbose debug tracing with full details')\n .helpOption('-h, --help', 'Display help')\n .allowUnknownOption(true)\n .action(async (_options) => {\n const claudeSM = new ClaudeSM();\n const args = process.argv.slice(2);\n await claudeSM.run(args);\n });\n\n// Handle direct execution\nif (require.main === module) {\n program.parse(process.argv);\n}\n"],
|
|
5
|
-
"mappings": ";AAOA,SAAS,OAAO,
|
|
4
|
+
"sourcesContent": ["#!/usr/bin/env node\n\n/**\n * claude-sm: Claude wrapper with StackMemory and worktree integration\n * Automatically manages context persistence and instance isolation\n */\n\nimport { spawn, execSync, execFileSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { program } from 'commander';\nimport { v4 as uuidv4 } from 'uuid';\nimport chalk from 'chalk';\nimport { initializeTracing, trace } from '../core/trace/index.js';\n\ninterface ClaudeConfig {\n instanceId: string;\n worktreePath?: string;\n useSandbox: boolean;\n useChrome: boolean;\n useWorktree: boolean;\n contextEnabled: boolean;\n branch?: string;\n task?: string;\n tracingEnabled: boolean;\n verboseTracing: boolean;\n}\n\nclass ClaudeSM {\n private config: ClaudeConfig;\n private stackmemoryPath: string;\n private worktreeScriptPath: string;\n private claudeConfigDir: string;\n\n constructor() {\n this.config = {\n instanceId: this.generateInstanceId(),\n useSandbox: false,\n useChrome: false,\n useWorktree: false,\n contextEnabled: true,\n tracingEnabled: true, // Enable tracing by default for claude-sm\n verboseTracing: false,\n };\n\n this.stackmemoryPath = this.findStackMemory();\n this.worktreeScriptPath = path.join(\n __dirname,\n '../../scripts/claude-worktree-manager.sh'\n );\n this.claudeConfigDir = path.join(os.homedir(), '.claude');\n\n // Ensure config directory exists\n if (!fs.existsSync(this.claudeConfigDir)) {\n fs.mkdirSync(this.claudeConfigDir, { recursive: true });\n }\n }\n\n private generateInstanceId(): string {\n return uuidv4().substring(0, 8);\n }\n\n private findStackMemory(): string {\n // Check multiple possible locations\n const possiblePaths = [\n path.join(os.homedir(), '.stackmemory', 'bin', 'stackmemory'),\n '/usr/local/bin/stackmemory',\n '/opt/homebrew/bin/stackmemory',\n 'stackmemory', // Rely on PATH\n ];\n\n for (const smPath of possiblePaths) {\n try {\n execFileSync('which', [smPath], { stdio: 'ignore' });\n return smPath;\n } catch {\n // Continue searching\n }\n }\n\n return 'stackmemory'; // Fallback to PATH\n }\n\n private isGitRepo(): boolean {\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n }\n\n private getCurrentBranch(): string {\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n encoding: 'utf8',\n }).trim();\n } catch {\n return 'main';\n }\n }\n\n private hasUncommittedChanges(): boolean {\n try {\n const status = execSync('git status --porcelain', { encoding: 'utf8' });\n return status.length > 0;\n } catch {\n return false;\n }\n }\n\n private setupWorktree(): string | null {\n if (!this.config.useWorktree || !this.isGitRepo()) {\n return null;\n }\n\n console.log(chalk.blue('\uD83C\uDF33 Setting up isolated worktree...'));\n\n const timestamp = new Date()\n .toISOString()\n .replace(/[:.]/g, '-')\n .substring(0, 19);\n const branch =\n this.config.branch ||\n `claude-${this.config.task || 'work'}-${timestamp}-${this.config.instanceId}`;\n const repoName = path.basename(process.cwd());\n const worktreePath = path.join(\n path.dirname(process.cwd()),\n `${repoName}--${branch}`\n );\n\n try {\n // Create worktree\n const flags = [];\n if (this.config.useSandbox) flags.push('--sandbox');\n if (this.config.useChrome) flags.push('--chrome');\n\n const cmd = `git worktree add -b \"${branch}\" \"${worktreePath}\"`;\n execSync(cmd, { stdio: 'inherit' });\n\n console.log(chalk.green(`\u2705 Worktree created: ${worktreePath}`));\n console.log(chalk.gray(` Branch: ${branch}`));\n\n // Save worktree config\n const configPath = path.join(worktreePath, '.claude-instance.json');\n const configData = {\n instanceId: this.config.instanceId,\n worktreePath,\n branch,\n task: this.config.task,\n sandboxEnabled: this.config.useSandbox,\n chromeEnabled: this.config.useChrome,\n created: new Date().toISOString(),\n parentRepo: process.cwd(),\n };\n fs.writeFileSync(configPath, JSON.stringify(configData, null, 2));\n\n // Copy environment files\n const envFiles = ['.env', '.env.local', '.mise.toml', '.tool-versions'];\n for (const file of envFiles) {\n const srcPath = path.join(process.cwd(), file);\n if (fs.existsSync(srcPath)) {\n fs.copyFileSync(srcPath, path.join(worktreePath, file));\n }\n }\n\n return worktreePath;\n } catch (err: unknown) {\n console.error(chalk.red('\u274C Failed to create worktree:'), err);\n return null;\n }\n }\n\n private saveContext(\n message: string,\n metadata: Record<string, unknown> = {}\n ): void {\n if (!this.config.contextEnabled) return;\n\n try {\n const contextData = {\n message,\n metadata: {\n ...metadata,\n instanceId: this.config.instanceId,\n worktree: this.config.worktreePath,\n timestamp: new Date().toISOString(),\n },\n };\n\n const cmd = `${this.stackmemoryPath} context save --json '${JSON.stringify(contextData)}'`;\n execSync(cmd, { stdio: 'ignore' });\n } catch {\n // Silently fail - don't interrupt Claude\n }\n }\n\n private loadContext(): void {\n if (!this.config.contextEnabled) return;\n\n try {\n console.log(chalk.blue('\uD83D\uDCDA Loading previous context...'));\n\n const cmd = `${this.stackmemoryPath} context list --limit 5 --format json`;\n const output = execSync(cmd, { encoding: 'utf8' });\n const contexts = JSON.parse(output);\n\n if (contexts.length > 0) {\n console.log(chalk.gray('Recent context loaded:'));\n contexts.forEach(\n (ctx: { message: string; metadata?: { timestamp?: string } }) => {\n console.log(\n chalk.gray(` - ${ctx.message} (${ctx.metadata?.timestamp})`)\n );\n }\n );\n }\n } catch {\n // Silently continue\n }\n }\n\n private detectMultipleInstances(): boolean {\n try {\n const lockDir = path.join(process.cwd(), '.claude-worktree-locks');\n if (!fs.existsSync(lockDir)) return false;\n\n const locks = fs.readdirSync(lockDir).filter((f) => f.endsWith('.lock'));\n const activeLocks = locks.filter((lockFile) => {\n const lockPath = path.join(lockDir, lockFile);\n const lockData = JSON.parse(fs.readFileSync(lockPath, 'utf8'));\n const lockAge = Date.now() - new Date(lockData.created).getTime();\n return lockAge < 24 * 60 * 60 * 1000; // Less than 24 hours old\n });\n\n return activeLocks.length > 0;\n } catch {\n return false;\n }\n }\n\n private suggestWorktreeMode(): void {\n if (this.hasUncommittedChanges()) {\n console.log(chalk.yellow('\u26A0\uFE0F Uncommitted changes detected'));\n console.log(\n chalk.gray(' Consider using --worktree to work in isolation')\n );\n }\n\n if (this.detectMultipleInstances()) {\n console.log(chalk.yellow('\u26A0\uFE0F Other Claude instances detected'));\n console.log(\n chalk.gray(' Using --worktree is recommended to avoid conflicts')\n );\n }\n }\n\n public async run(args: string[]): Promise<void> {\n // Parse arguments\n const claudeArgs: string[] = [];\n let i = 0;\n\n while (i < args.length) {\n const arg = args[i];\n\n switch (arg) {\n case '--worktree':\n case '-w':\n this.config.useWorktree = true;\n break;\n case '--sandbox':\n case '-s':\n this.config.useSandbox = true;\n claudeArgs.push('--sandbox');\n break;\n case '--chrome':\n case '-c':\n this.config.useChrome = true;\n claudeArgs.push('--chrome');\n break;\n case '--no-context':\n this.config.contextEnabled = false;\n break;\n case '--no-trace':\n this.config.tracingEnabled = false;\n break;\n case '--verbose-trace':\n this.config.verboseTracing = true;\n break;\n case '--branch':\n case '-b':\n i++;\n this.config.branch = args[i];\n break;\n case '--task':\n case '-t':\n i++;\n this.config.task = args[i];\n break;\n case '--auto':\n case '-a':\n // Auto mode: detect and apply best settings\n if (this.isGitRepo()) {\n this.config.useWorktree =\n this.hasUncommittedChanges() || this.detectMultipleInstances();\n }\n break;\n default:\n claudeArgs.push(arg);\n }\n i++;\n }\n\n // Initialize tracing system if enabled\n if (this.config.tracingEnabled) {\n // Set up environment for tracing\n process.env['DEBUG_TRACE'] = 'true';\n process.env['STACKMEMORY_DEBUG'] = 'true';\n process.env['TRACE_OUTPUT'] = 'file'; // Write to file to not clutter Claude output\n process.env['TRACE_MASK_SENSITIVE'] = 'true'; // Always mask sensitive data\n\n if (this.config.verboseTracing) {\n process.env['TRACE_VERBOSITY'] = 'full';\n process.env['TRACE_PARAMS'] = 'true';\n process.env['TRACE_RESULTS'] = 'true';\n process.env['TRACE_MEMORY'] = 'true';\n } else {\n process.env['TRACE_VERBOSITY'] = 'summary';\n process.env['TRACE_PARAMS'] = 'true';\n process.env['TRACE_RESULTS'] = 'false';\n }\n\n // Initialize the tracing system\n initializeTracing();\n\n // Start tracing this Claude session\n trace.command(\n 'claude-sm',\n {\n instanceId: this.config.instanceId,\n worktree: this.config.useWorktree,\n sandbox: this.config.useSandbox,\n task: this.config.task,\n },\n async () => {\n // Session tracing will wrap the entire Claude execution\n }\n );\n }\n\n // Show header\n console.log(chalk.blue('\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557'));\n console.log(chalk.blue('\u2551 Claude + StackMemory + Worktree \u2551'));\n console.log(chalk.blue('\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D'));\n console.log();\n\n // Check Git repo status\n if (this.isGitRepo()) {\n const branch = this.getCurrentBranch();\n console.log(chalk.gray(`\uD83D\uDCCD Current branch: ${branch}`));\n\n if (!this.config.useWorktree) {\n this.suggestWorktreeMode();\n }\n }\n\n // Setup worktree if requested\n if (this.config.useWorktree) {\n const worktreePath = this.setupWorktree();\n if (worktreePath) {\n this.config.worktreePath = worktreePath;\n process.chdir(worktreePath);\n\n // Save context about worktree creation\n this.saveContext('Created worktree for Claude instance', {\n action: 'worktree_created',\n path: worktreePath,\n branch: this.config.branch,\n });\n }\n }\n\n // Load previous context\n this.loadContext();\n\n // Setup environment\n process.env['CLAUDE_INSTANCE_ID'] = this.config.instanceId;\n if (this.config.worktreePath) {\n process.env['CLAUDE_WORKTREE_PATH'] = this.config.worktreePath;\n }\n\n console.log(chalk.gray(`\uD83E\uDD16 Instance ID: ${this.config.instanceId}`));\n console.log(chalk.gray(`\uD83D\uDCC1 Working in: ${process.cwd()}`));\n\n if (this.config.useSandbox) {\n console.log(chalk.yellow('\uD83D\uDD12 Sandbox mode enabled'));\n }\n if (this.config.useChrome) {\n console.log(chalk.yellow('\uD83C\uDF10 Chrome automation enabled'));\n }\n if (this.config.tracingEnabled) {\n console.log(\n chalk.gray(`\uD83D\uDD0D Debug tracing enabled (logs to ~/.stackmemory/traces/)`)\n );\n if (this.config.verboseTracing) {\n console.log(\n chalk.gray(` Verbose mode: capturing all execution details`)\n );\n }\n }\n\n console.log();\n console.log(chalk.gray('Starting Claude...'));\n console.log(chalk.gray('\u2500'.repeat(42)));\n\n // Launch Claude\n const claude = spawn('claude', claudeArgs, {\n stdio: 'inherit',\n env: process.env,\n });\n\n // Handle exit\n claude.on('exit', (code) => {\n // Save final context\n this.saveContext('Claude session ended', {\n action: 'session_end',\n exitCode: code,\n });\n\n // End tracing and show summary if enabled\n if (this.config.tracingEnabled) {\n const summary = trace.getExecutionSummary();\n console.log();\n console.log(chalk.gray('\u2500'.repeat(42)));\n console.log(chalk.blue('Debug Trace Summary:'));\n console.log(chalk.gray(summary));\n }\n\n // Offer to clean up worktree\n if (this.config.worktreePath) {\n console.log();\n console.log(chalk.gray('\u2500'.repeat(42)));\n console.log(chalk.blue('Session ended in worktree:'));\n console.log(chalk.gray(` ${this.config.worktreePath}`));\n console.log();\n console.log(chalk.gray('To remove worktree: gd_claude'));\n console.log(chalk.gray('To merge to main: cwm'));\n }\n\n process.exit(code || 0);\n });\n\n // Handle signals\n process.on('SIGINT', () => {\n this.saveContext('Claude session interrupted', {\n action: 'session_interrupt',\n });\n claude.kill('SIGINT');\n });\n\n process.on('SIGTERM', () => {\n this.saveContext('Claude session terminated', {\n action: 'session_terminate',\n });\n claude.kill('SIGTERM');\n });\n }\n}\n\n// CLI interface\nprogram\n .name('claude-sm')\n .description('Claude with StackMemory context and worktree isolation')\n .version('1.0.0')\n .option('-w, --worktree', 'Create isolated worktree for this instance')\n .option('-s, --sandbox', 'Enable sandbox mode (file/network restrictions)')\n .option('-c, --chrome', 'Enable Chrome automation')\n .option('-a, --auto', 'Automatically detect and apply best settings')\n .option('-b, --branch <name>', 'Specify branch name for worktree')\n .option('-t, --task <desc>', 'Task description for context')\n .option('--no-context', 'Disable StackMemory context integration')\n .option('--no-trace', 'Disable debug tracing (enabled by default)')\n .option('--verbose-trace', 'Enable verbose debug tracing with full details')\n .helpOption('-h, --help', 'Display help')\n .allowUnknownOption(true)\n .action(async (_options) => {\n const claudeSM = new ClaudeSM();\n const args = process.argv.slice(2);\n await claudeSM.run(args);\n });\n\n// Handle direct execution\nif (require.main === module) {\n program.parse(process.argv);\n}\n"],
|
|
5
|
+
"mappings": ";AAOA,SAAS,OAAO,UAAU,oBAAoB;AAC9C,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,YAAY,QAAQ;AACpB,SAAS,eAAe;AACxB,SAAS,MAAM,cAAc;AAC7B,OAAO,WAAW;AAClB,SAAS,mBAAmB,aAAa;AAezC,MAAM,SAAS;AAAA,EACL;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAER,cAAc;AACZ,SAAK,SAAS;AAAA,MACZ,YAAY,KAAK,mBAAmB;AAAA,MACpC,YAAY;AAAA,MACZ,WAAW;AAAA,MACX,aAAa;AAAA,MACb,gBAAgB;AAAA,MAChB,gBAAgB;AAAA;AAAA,MAChB,gBAAgB;AAAA,IAClB;AAEA,SAAK,kBAAkB,KAAK,gBAAgB;AAC5C,SAAK,qBAAqB,KAAK;AAAA,MAC7B;AAAA,MACA;AAAA,IACF;AACA,SAAK,kBAAkB,KAAK,KAAK,GAAG,QAAQ,GAAG,SAAS;AAGxD,QAAI,CAAC,GAAG,WAAW,KAAK,eAAe,GAAG;AACxC,SAAG,UAAU,KAAK,iBAAiB,EAAE,WAAW,KAAK,CAAC;AAAA,IACxD;AAAA,EACF;AAAA,EAEQ,qBAA6B;AACnC,WAAO,OAAO,EAAE,UAAU,GAAG,CAAC;AAAA,EAChC;AAAA,EAEQ,kBAA0B;AAEhC,UAAM,gBAAgB;AAAA,MACpB,KAAK,KAAK,GAAG,QAAQ,GAAG,gBAAgB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AAc,4CAA4C,EACjE,OAAO,mBAAmB,gDAAgD,EAC1E,WAAW,cAAc,cAAc,EACvC,mBAAmB,IAAI,EACvB,OAAO,OAAO,aAAa;AAC1B,QAAM,WAAW,IAAI,SAAS;AAC9B,QAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,QAAM,SAAS,IAAI,IAAI;AACzB,CAAC;AAGH,IAAI,QAAQ,SAAS,QAAQ;AAC3B,UAAQ,MAAM,QAAQ,IAAI;AAC5B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/cli/codex-sm.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { spawn, execSync } from "child_process";
|
|
2
|
+
import { spawn, execSync, execFileSync } from "child_process";
|
|
3
3
|
import * as fs from "fs";
|
|
4
4
|
import * as path from "path";
|
|
5
5
|
import * as os from "os";
|
|
@@ -32,7 +32,7 @@ class CodexSM {
|
|
|
32
32
|
];
|
|
33
33
|
for (const smPath of possiblePaths) {
|
|
34
34
|
try {
|
|
35
|
-
|
|
35
|
+
execFileSync("which", [smPath], { stdio: "ignore" });
|
|
36
36
|
return smPath;
|
|
37
37
|
} catch {
|
|
38
38
|
}
|
package/dist/cli/codex-sm.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/cli/codex-sm.ts"],
|
|
4
|
-
"sourcesContent": ["#!/usr/bin/env node\n\n/**\n * codex-sm: Codex wrapper with StackMemory and worktree integration\n * Automatically manages context persistence, optional worktree isolation, and tracing\n */\n\nimport { spawn, execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { program } from 'commander';\nimport { v4 as uuidv4 } from 'uuid';\nimport chalk from 'chalk';\nimport { initializeTracing, trace } from '../core/trace/index.js';\n\ninterface CodexConfig {\n instanceId: string;\n worktreePath?: string;\n useWorktree: boolean;\n contextEnabled: boolean;\n branch?: string;\n task?: string;\n tracingEnabled: boolean;\n verboseTracing: boolean;\n}\n\nclass CodexSM {\n private config: CodexConfig;\n private stackmemoryPath: string;\n\n constructor() {\n this.config = {\n instanceId: this.generateInstanceId(),\n useWorktree: false,\n contextEnabled: true,\n tracingEnabled: true,\n verboseTracing: false,\n };\n\n this.stackmemoryPath = this.findStackMemory();\n }\n\n private generateInstanceId(): string {\n return uuidv4().substring(0, 8);\n }\n\n private findStackMemory(): string {\n const possiblePaths = [\n path.join(os.homedir(), '.stackmemory', 'bin', 'stackmemory'),\n '/usr/local/bin/stackmemory',\n '/opt/homebrew/bin/stackmemory',\n 'stackmemory',\n ];\n for (const smPath of possiblePaths) {\n try {\n execSync(`which ${smPath}`, { stdio: 'ignore' });\n return smPath;\n } catch {\n // continue\n }\n }\n return 'stackmemory';\n }\n\n private isGitRepo(): boolean {\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n }\n\n private getCurrentBranch(): string {\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n encoding: 'utf8',\n }).trim();\n } catch {\n return 'main';\n }\n }\n\n private hasUncommittedChanges(): boolean {\n try {\n const status = execSync('git status --porcelain', { encoding: 'utf8' });\n return status.length > 0;\n } catch {\n return false;\n }\n }\n\n private setupWorktree(): string | null {\n if (!this.config.useWorktree || !this.isGitRepo()) return null;\n\n console.log(chalk.blue('\uD83C\uDF33 Setting up isolated worktree...'));\n\n const timestamp = new Date()\n .toISOString()\n .replace(/[:.]/g, '-')\n .substring(0, 19);\n const branch =\n this.config.branch ||\n `codex-${this.config.task || 'work'}-${timestamp}-${this.config.instanceId}`;\n const repoName = path.basename(process.cwd());\n const worktreePath = path.join(\n path.dirname(process.cwd()),\n `${repoName}--${branch}`\n );\n\n try {\n const cmd = `git worktree add -b \"${branch}\" \"${worktreePath}\"`;\n execSync(cmd, { stdio: 'inherit' });\n\n console.log(chalk.green(`\u2705 Worktree created: ${worktreePath}`));\n console.log(chalk.gray(` Branch: ${branch}`));\n\n const configPath = path.join(worktreePath, '.codex-instance.json');\n const configData = {\n instanceId: this.config.instanceId,\n worktreePath,\n branch,\n task: this.config.task,\n created: new Date().toISOString(),\n parentRepo: process.cwd(),\n };\n fs.writeFileSync(configPath, JSON.stringify(configData, null, 2));\n\n const envFiles = ['.env', '.env.local', '.mise.toml', '.tool-versions'];\n for (const file of envFiles) {\n const srcPath = path.join(process.cwd(), file);\n if (fs.existsSync(srcPath))\n fs.copyFileSync(srcPath, path.join(worktreePath, file));\n }\n\n return worktreePath;\n } catch (err: unknown) {\n console.error(chalk.red('\u274C Failed to create worktree:'), err);\n return null;\n }\n }\n\n private saveContext(\n message: string,\n metadata: Record<string, unknown> = {}\n ): void {\n if (!this.config.contextEnabled) return;\n try {\n const contextData = {\n message,\n metadata: {\n ...metadata,\n instanceId: this.config.instanceId,\n worktree: this.config.worktreePath,\n timestamp: new Date().toISOString(),\n },\n };\n const cmd = `${this.stackmemoryPath} context save --json '${JSON.stringify(contextData)}'`;\n execSync(cmd, { stdio: 'ignore' });\n } catch {\n // ignore\n }\n }\n\n private loadContext(): void {\n if (!this.config.contextEnabled) return;\n try {\n console.log(chalk.blue('\uD83D\uDCDA Loading previous context...'));\n const cmd = `${this.stackmemoryPath} context list --limit 5 --format json`;\n const output = execSync(cmd, { encoding: 'utf8' });\n const contexts = JSON.parse(output);\n if (Array.isArray(contexts) && contexts.length > 0) {\n console.log(chalk.gray('Recent context loaded:'));\n contexts.forEach(\n (ctx: { message: string; metadata?: { timestamp?: string } }) => {\n console.log(\n chalk.gray(` - ${ctx.message} (${ctx.metadata?.timestamp})`)\n );\n }\n );\n }\n } catch {\n // ignore\n }\n }\n\n private suggestWorktreeMode(): void {\n if (this.hasUncommittedChanges()) {\n console.log(chalk.yellow('\u26A0\uFE0F Uncommitted changes detected'));\n console.log(\n chalk.gray(' Consider using --worktree to work in isolation')\n );\n }\n }\n\n public async run(args: string[]): Promise<void> {\n const codexArgs: string[] = [];\n let i = 0;\n while (i < args.length) {\n const arg = args[i];\n switch (arg) {\n case '--worktree':\n case '-w':\n this.config.useWorktree = true;\n break;\n case '--no-context':\n this.config.contextEnabled = false;\n break;\n case '--no-trace':\n this.config.tracingEnabled = false;\n break;\n case '--verbose-trace':\n this.config.verboseTracing = true;\n break;\n case '--branch':\n case '-b':\n i++;\n this.config.branch = args[i];\n break;\n case '--task':\n case '-t':\n i++;\n this.config.task = args[i];\n break;\n case '--auto':\n case '-a':\n if (this.isGitRepo()) {\n this.config.useWorktree = this.hasUncommittedChanges();\n }\n break;\n default:\n codexArgs.push(arg);\n }\n i++;\n }\n\n if (this.config.tracingEnabled) {\n process.env['DEBUG_TRACE'] = 'true';\n process.env['STACKMEMORY_DEBUG'] = 'true';\n process.env['TRACE_OUTPUT'] = 'file';\n process.env['TRACE_MASK_SENSITIVE'] = 'true';\n if (this.config.verboseTracing) {\n process.env['TRACE_VERBOSITY'] = 'full';\n process.env['TRACE_PARAMS'] = 'true';\n process.env['TRACE_RESULTS'] = 'true';\n process.env['TRACE_MEMORY'] = 'true';\n } else {\n process.env['TRACE_VERBOSITY'] = 'summary';\n process.env['TRACE_PARAMS'] = 'true';\n process.env['TRACE_RESULTS'] = 'false';\n }\n initializeTracing();\n trace.command(\n 'codex-sm',\n {\n instanceId: this.config.instanceId,\n worktree: this.config.useWorktree,\n task: this.config.task,\n },\n async () => {}\n );\n }\n\n console.log(chalk.blue('\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557'));\n console.log(chalk.blue('\u2551 Codex + StackMemory + Worktree \u2551'));\n console.log(chalk.blue('\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D'));\n console.log();\n\n if (this.isGitRepo()) {\n const branch = this.getCurrentBranch();\n console.log(chalk.gray(`\uD83D\uDCCD Current branch: ${branch}`));\n if (!this.config.useWorktree) this.suggestWorktreeMode();\n }\n\n if (this.config.useWorktree) {\n const worktreePath = this.setupWorktree();\n if (worktreePath) {\n this.config.worktreePath = worktreePath;\n process.chdir(worktreePath);\n this.saveContext('Created worktree for Codex instance', {\n action: 'worktree_created',\n path: worktreePath,\n branch: this.config.branch,\n });\n }\n }\n\n this.loadContext();\n\n process.env['CODEX_INSTANCE_ID'] = this.config.instanceId;\n if (this.config.worktreePath)\n process.env['CODEX_WORKTREE_PATH'] = this.config.worktreePath;\n\n console.log(chalk.gray(`\uD83E\uDD16 Instance ID: ${this.config.instanceId}`));\n console.log(chalk.gray(`\uD83D\uDCC1 Working in: ${process.cwd()}`));\n\n console.log();\n console.log(chalk.gray('Starting Codex...'));\n console.log(chalk.gray('\u2500'.repeat(42)));\n\n const codexBin = (() => {\n try {\n execSync('which codex', { stdio: 'ignore' });\n return 'codex';\n } catch {}\n try {\n execSync('which codex-cli', { stdio: 'ignore' });\n return 'codex-cli';\n } catch {}\n return null;\n })();\n\n if (!codexBin) {\n console.error(\n chalk.red('\u274C Codex CLI not found in PATH (codex or codex-cli).')\n );\n process.exit(1);\n return;\n }\n\n const child = spawn(codexBin, codexArgs, {\n stdio: 'inherit',\n env: process.env,\n });\n\n child.on('exit', (code) => {\n this.saveContext('Codex session ended', {\n action: 'session_end',\n exitCode: code,\n });\n if (this.config.tracingEnabled) {\n const summary = trace.getExecutionSummary();\n console.log();\n console.log(chalk.gray('\u2500'.repeat(42)));\n console.log(chalk.blue('Debug Trace Summary:'));\n console.log(chalk.gray(summary));\n }\n if (this.config.worktreePath) {\n console.log();\n console.log(chalk.gray('\u2500'.repeat(42)));\n console.log(chalk.blue('Session ended in worktree:'));\n console.log(chalk.gray(` ${this.config.worktreePath}`));\n }\n process.exit(code || 0);\n });\n\n process.on('SIGINT', () => {\n this.saveContext('Codex session interrupted', {\n action: 'session_interrupt',\n });\n child.kill('SIGINT');\n });\n\n process.on('SIGTERM', () => {\n this.saveContext('Codex session terminated', {\n action: 'session_terminate',\n });\n child.kill('SIGTERM');\n });\n }\n}\n\nprogram\n .name('codex-sm')\n .description('Codex with StackMemory context and optional worktree isolation')\n .version('1.0.0')\n .option('-w, --worktree', 'Create isolated worktree for this instance')\n .option('-a, --auto', 'Automatically detect and apply best settings')\n .option('-b, --branch <name>', 'Specify branch name for worktree')\n .option('-t, --task <desc>', 'Task description for context')\n .option('--no-context', 'Disable StackMemory context integration')\n .option('--no-trace', 'Disable debug tracing (enabled by default)')\n .option('--verbose-trace', 'Enable verbose debug tracing with full details')\n .helpOption('-h, --help', 'Display help')\n .allowUnknownOption(true)\n .action(async (_options) => {\n const codexSM = new CodexSM();\n const args = process.argv.slice(2);\n await codexSM.run(args);\n });\n\nif (require.main === module) {\n program.parse(process.argv);\n}\n"],
|
|
5
|
-
"mappings": ";AAOA,SAAS,OAAO,
|
|
4
|
+
"sourcesContent": ["#!/usr/bin/env node\n\n/**\n * codex-sm: Codex wrapper with StackMemory and worktree integration\n * Automatically manages context persistence, optional worktree isolation, and tracing\n */\n\nimport { spawn, execSync, execFileSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { program } from 'commander';\nimport { v4 as uuidv4 } from 'uuid';\nimport chalk from 'chalk';\nimport { initializeTracing, trace } from '../core/trace/index.js';\n\ninterface CodexConfig {\n instanceId: string;\n worktreePath?: string;\n useWorktree: boolean;\n contextEnabled: boolean;\n branch?: string;\n task?: string;\n tracingEnabled: boolean;\n verboseTracing: boolean;\n}\n\nclass CodexSM {\n private config: CodexConfig;\n private stackmemoryPath: string;\n\n constructor() {\n this.config = {\n instanceId: this.generateInstanceId(),\n useWorktree: false,\n contextEnabled: true,\n tracingEnabled: true,\n verboseTracing: false,\n };\n\n this.stackmemoryPath = this.findStackMemory();\n }\n\n private generateInstanceId(): string {\n return uuidv4().substring(0, 8);\n }\n\n private findStackMemory(): string {\n const possiblePaths = [\n path.join(os.homedir(), '.stackmemory', 'bin', 'stackmemory'),\n '/usr/local/bin/stackmemory',\n '/opt/homebrew/bin/stackmemory',\n 'stackmemory',\n ];\n for (const smPath of possiblePaths) {\n try {\n execFileSync('which', [smPath], { stdio: 'ignore' });\n return smPath;\n } catch {\n // continue\n }\n }\n return 'stackmemory';\n }\n\n private isGitRepo(): boolean {\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n }\n\n private getCurrentBranch(): string {\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n encoding: 'utf8',\n }).trim();\n } catch {\n return 'main';\n }\n }\n\n private hasUncommittedChanges(): boolean {\n try {\n const status = execSync('git status --porcelain', { encoding: 'utf8' });\n return status.length > 0;\n } catch {\n return false;\n }\n }\n\n private setupWorktree(): string | null {\n if (!this.config.useWorktree || !this.isGitRepo()) return null;\n\n console.log(chalk.blue('\uD83C\uDF33 Setting up isolated worktree...'));\n\n const timestamp = new Date()\n .toISOString()\n .replace(/[:.]/g, '-')\n .substring(0, 19);\n const branch =\n this.config.branch ||\n `codex-${this.config.task || 'work'}-${timestamp}-${this.config.instanceId}`;\n const repoName = path.basename(process.cwd());\n const worktreePath = path.join(\n path.dirname(process.cwd()),\n `${repoName}--${branch}`\n );\n\n try {\n const cmd = `git worktree add -b \"${branch}\" \"${worktreePath}\"`;\n execSync(cmd, { stdio: 'inherit' });\n\n console.log(chalk.green(`\u2705 Worktree created: ${worktreePath}`));\n console.log(chalk.gray(` Branch: ${branch}`));\n\n const configPath = path.join(worktreePath, '.codex-instance.json');\n const configData = {\n instanceId: this.config.instanceId,\n worktreePath,\n branch,\n task: this.config.task,\n created: new Date().toISOString(),\n parentRepo: process.cwd(),\n };\n fs.writeFileSync(configPath, JSON.stringify(configData, null, 2));\n\n const envFiles = ['.env', '.env.local', '.mise.toml', '.tool-versions'];\n for (const file of envFiles) {\n const srcPath = path.join(process.cwd(), file);\n if (fs.existsSync(srcPath))\n fs.copyFileSync(srcPath, path.join(worktreePath, file));\n }\n\n return worktreePath;\n } catch (err: unknown) {\n console.error(chalk.red('\u274C Failed to create worktree:'), err);\n return null;\n }\n }\n\n private saveContext(\n message: string,\n metadata: Record<string, unknown> = {}\n ): void {\n if (!this.config.contextEnabled) return;\n try {\n const contextData = {\n message,\n metadata: {\n ...metadata,\n instanceId: this.config.instanceId,\n worktree: this.config.worktreePath,\n timestamp: new Date().toISOString(),\n },\n };\n const cmd = `${this.stackmemoryPath} context save --json '${JSON.stringify(contextData)}'`;\n execSync(cmd, { stdio: 'ignore' });\n } catch {\n // ignore\n }\n }\n\n private loadContext(): void {\n if (!this.config.contextEnabled) return;\n try {\n console.log(chalk.blue('\uD83D\uDCDA Loading previous context...'));\n const cmd = `${this.stackmemoryPath} context list --limit 5 --format json`;\n const output = execSync(cmd, { encoding: 'utf8' });\n const contexts = JSON.parse(output);\n if (Array.isArray(contexts) && contexts.length > 0) {\n console.log(chalk.gray('Recent context loaded:'));\n contexts.forEach(\n (ctx: { message: string; metadata?: { timestamp?: string } }) => {\n console.log(\n chalk.gray(` - ${ctx.message} (${ctx.metadata?.timestamp})`)\n );\n }\n );\n }\n } catch {\n // ignore\n }\n }\n\n private suggestWorktreeMode(): void {\n if (this.hasUncommittedChanges()) {\n console.log(chalk.yellow('\u26A0\uFE0F Uncommitted changes detected'));\n console.log(\n chalk.gray(' Consider using --worktree to work in isolation')\n );\n }\n }\n\n public async run(args: string[]): Promise<void> {\n const codexArgs: string[] = [];\n let i = 0;\n while (i < args.length) {\n const arg = args[i];\n switch (arg) {\n case '--worktree':\n case '-w':\n this.config.useWorktree = true;\n break;\n case '--no-context':\n this.config.contextEnabled = false;\n break;\n case '--no-trace':\n this.config.tracingEnabled = false;\n break;\n case '--verbose-trace':\n this.config.verboseTracing = true;\n break;\n case '--branch':\n case '-b':\n i++;\n this.config.branch = args[i];\n break;\n case '--task':\n case '-t':\n i++;\n this.config.task = args[i];\n break;\n case '--auto':\n case '-a':\n if (this.isGitRepo()) {\n this.config.useWorktree = this.hasUncommittedChanges();\n }\n break;\n default:\n codexArgs.push(arg);\n }\n i++;\n }\n\n if (this.config.tracingEnabled) {\n process.env['DEBUG_TRACE'] = 'true';\n process.env['STACKMEMORY_DEBUG'] = 'true';\n process.env['TRACE_OUTPUT'] = 'file';\n process.env['TRACE_MASK_SENSITIVE'] = 'true';\n if (this.config.verboseTracing) {\n process.env['TRACE_VERBOSITY'] = 'full';\n process.env['TRACE_PARAMS'] = 'true';\n process.env['TRACE_RESULTS'] = 'true';\n process.env['TRACE_MEMORY'] = 'true';\n } else {\n process.env['TRACE_VERBOSITY'] = 'summary';\n process.env['TRACE_PARAMS'] = 'true';\n process.env['TRACE_RESULTS'] = 'false';\n }\n initializeTracing();\n trace.command(\n 'codex-sm',\n {\n instanceId: this.config.instanceId,\n worktree: this.config.useWorktree,\n task: this.config.task,\n },\n async () => {}\n );\n }\n\n console.log(chalk.blue('\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557'));\n console.log(chalk.blue('\u2551 Codex + StackMemory + Worktree \u2551'));\n console.log(chalk.blue('\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D'));\n console.log();\n\n if (this.isGitRepo()) {\n const branch = this.getCurrentBranch();\n console.log(chalk.gray(`\uD83D\uDCCD Current branch: ${branch}`));\n if (!this.config.useWorktree) this.suggestWorktreeMode();\n }\n\n if (this.config.useWorktree) {\n const worktreePath = this.setupWorktree();\n if (worktreePath) {\n this.config.worktreePath = worktreePath;\n process.chdir(worktreePath);\n this.saveContext('Created worktree for Codex instance', {\n action: 'worktree_created',\n path: worktreePath,\n branch: this.config.branch,\n });\n }\n }\n\n this.loadContext();\n\n process.env['CODEX_INSTANCE_ID'] = this.config.instanceId;\n if (this.config.worktreePath)\n process.env['CODEX_WORKTREE_PATH'] = this.config.worktreePath;\n\n console.log(chalk.gray(`\uD83E\uDD16 Instance ID: ${this.config.instanceId}`));\n console.log(chalk.gray(`\uD83D\uDCC1 Working in: ${process.cwd()}`));\n\n console.log();\n console.log(chalk.gray('Starting Codex...'));\n console.log(chalk.gray('\u2500'.repeat(42)));\n\n const codexBin = (() => {\n try {\n execSync('which codex', { stdio: 'ignore' });\n return 'codex';\n } catch {}\n try {\n execSync('which codex-cli', { stdio: 'ignore' });\n return 'codex-cli';\n } catch {}\n return null;\n })();\n\n if (!codexBin) {\n console.error(\n chalk.red('\u274C Codex CLI not found in PATH (codex or codex-cli).')\n );\n process.exit(1);\n return;\n }\n\n const child = spawn(codexBin, codexArgs, {\n stdio: 'inherit',\n env: process.env,\n });\n\n child.on('exit', (code) => {\n this.saveContext('Codex session ended', {\n action: 'session_end',\n exitCode: code,\n });\n if (this.config.tracingEnabled) {\n const summary = trace.getExecutionSummary();\n console.log();\n console.log(chalk.gray('\u2500'.repeat(42)));\n console.log(chalk.blue('Debug Trace Summary:'));\n console.log(chalk.gray(summary));\n }\n if (this.config.worktreePath) {\n console.log();\n console.log(chalk.gray('\u2500'.repeat(42)));\n console.log(chalk.blue('Session ended in worktree:'));\n console.log(chalk.gray(` ${this.config.worktreePath}`));\n }\n process.exit(code || 0);\n });\n\n process.on('SIGINT', () => {\n this.saveContext('Codex session interrupted', {\n action: 'session_interrupt',\n });\n child.kill('SIGINT');\n });\n\n process.on('SIGTERM', () => {\n this.saveContext('Codex session terminated', {\n action: 'session_terminate',\n });\n child.kill('SIGTERM');\n });\n }\n}\n\nprogram\n .name('codex-sm')\n .description('Codex with StackMemory context and optional worktree isolation')\n .version('1.0.0')\n .option('-w, --worktree', 'Create isolated worktree for this instance')\n .option('-a, --auto', 'Automatically detect and apply best settings')\n .option('-b, --branch <name>', 'Specify branch name for worktree')\n .option('-t, --task <desc>', 'Task description for context')\n .option('--no-context', 'Disable StackMemory context integration')\n .option('--no-trace', 'Disable debug tracing (enabled by default)')\n .option('--verbose-trace', 'Enable verbose debug tracing with full details')\n .helpOption('-h, --help', 'Display help')\n .allowUnknownOption(true)\n .action(async (_options) => {\n const codexSM = new CodexSM();\n const args = process.argv.slice(2);\n await codexSM.run(args);\n });\n\nif (require.main === module) {\n program.parse(process.argv);\n}\n"],
|
|
5
|
+
"mappings": ";AAOA,SAAS,OAAO,UAAU,oBAAoB;AAC9C,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,YAAY,QAAQ;AACpB,SAAS,eAAe;AACxB,SAAS,MAAM,cAAc;AAC7B,OAAO,WAAW;AAClB,SAAS,mBAAmB,aAAa;AAazC,MAAM,QAAQ;AAAA,EACJ;AAAA,EACA;AAAA,EAER,cAAc;AACZ,SAAK,SAAS;AAAA,MACZ,YAAY,KAAK,mBAAmB;AAAA,MACpC,aAAa;AAAA,MACb,gBAAgB;AAAA,MAChB,gBAAgB;AAAA,MAChB,gBAAgB;AAAA,IAClB;AAEA,SAAK,kBAAkB,KAAK,gBAAgB;AAAA,EAC9C;AAAA,EAEQ,qBAA6B;AACnC,WAAO,OAAO,EAAE,UAAU,GAAG,CAAC;AAAA,EAChC;AAAA,EAEQ,kBAA0B;AAChC,UAAM,gBAAgB;AAAA,MACpB,KAAK,KAAK,GAAG,QAAQ,GAAG,gBAAgB,OAAO,aAAa;AAAA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AAM,CAAC;AACjC,QAAM,QAAQ,IAAI,IAAI;AACxB,CAAC;AAEH,IAAI,QAAQ,SAAS,QAAQ;AAC3B,UAAQ,MAAM,QAAQ,IAAI;AAC5B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { Command } from "commander";
|
|
2
|
-
import { execSync } from "child_process";
|
|
2
|
+
import { execSync, execFileSync } from "child_process";
|
|
3
3
|
import { existsSync, readFileSync, writeFileSync } from "fs";
|
|
4
4
|
import { join } from "path";
|
|
5
5
|
import Database from "better-sqlite3";
|
|
6
|
+
import { z } from "zod";
|
|
6
7
|
import { FrameManager } from "../../core/context/frame-manager.js";
|
|
7
8
|
import { PebblesTaskStore } from "../../features/tasks/pebbles-task-store.js";
|
|
8
9
|
import { logger } from "../../core/monitoring/logger.js";
|
|
10
|
+
const CommitMessageSchema = z.string().min(1, "Commit message cannot be empty").max(200, "Commit message too long").regex(/^[a-zA-Z0-9\s\-_.,:()\/\[\]]+$/, "Commit message contains invalid characters").refine((msg) => !msg.includes("\n"), "Commit message cannot contain newlines").refine((msg) => !msg.includes('"'), "Commit message cannot contain double quotes").refine((msg) => !msg.includes("`"), "Commit message cannot contain backticks");
|
|
9
11
|
function getEnv(key, defaultValue) {
|
|
10
12
|
const value = process.env[key];
|
|
11
13
|
if (value === void 0) {
|
|
@@ -42,8 +44,17 @@ function createHandoffCommand() {
|
|
|
42
44
|
cwd: projectRoot
|
|
43
45
|
}).trim();
|
|
44
46
|
execSync("git add -A", { cwd: projectRoot });
|
|
45
|
-
|
|
46
|
-
|
|
47
|
+
let commitMessage = options.message || `chore: handoff checkpoint on ${currentBranch}`;
|
|
48
|
+
try {
|
|
49
|
+
commitMessage = CommitMessageSchema.parse(commitMessage);
|
|
50
|
+
} catch (validationError) {
|
|
51
|
+
console.error("\u274C Invalid commit message:", validationError.message);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
execFileSync("git", ["commit", "-m", commitMessage], {
|
|
55
|
+
cwd: projectRoot,
|
|
56
|
+
stdio: "inherit"
|
|
57
|
+
});
|
|
47
58
|
console.log(`\u2705 Committed changes: "${commitMessage}"`);
|
|
48
59
|
console.log(` Branch: ${currentBranch}`);
|
|
49
60
|
} catch (err) {
|
|
@@ -192,11 +203,22 @@ Generated by stackmemory handoff at ${timestamp}
|
|
|
192
203
|
console.log("=".repeat(60));
|
|
193
204
|
if (options.copy) {
|
|
194
205
|
try {
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
206
|
+
if (process.platform === "darwin") {
|
|
207
|
+
execFileSync("pbcopy", [], {
|
|
208
|
+
input: handoffPrompt,
|
|
209
|
+
cwd: projectRoot
|
|
210
|
+
});
|
|
211
|
+
} else if (process.platform === "win32") {
|
|
212
|
+
execFileSync("clip", [], {
|
|
213
|
+
input: handoffPrompt,
|
|
214
|
+
cwd: projectRoot
|
|
215
|
+
});
|
|
216
|
+
} else {
|
|
217
|
+
execFileSync("xclip", ["-selection", "clipboard"], {
|
|
218
|
+
input: handoffPrompt,
|
|
219
|
+
cwd: projectRoot
|
|
220
|
+
});
|
|
221
|
+
}
|
|
200
222
|
console.log("\n\u2705 Handoff prompt copied to clipboard!");
|
|
201
223
|
} catch (err) {
|
|
202
224
|
console.log("\n\u26A0\uFE0F Could not copy to clipboard");
|
|
@@ -256,11 +278,22 @@ Generated by stackmemory handoff at ${timestamp}
|
|
|
256
278
|
}
|
|
257
279
|
if (options.copy !== false) {
|
|
258
280
|
try {
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
281
|
+
if (process.platform === "darwin") {
|
|
282
|
+
execFileSync("pbcopy", [], {
|
|
283
|
+
input: handoffPrompt,
|
|
284
|
+
cwd: projectRoot
|
|
285
|
+
});
|
|
286
|
+
} else if (process.platform === "win32") {
|
|
287
|
+
execFileSync("clip", [], {
|
|
288
|
+
input: handoffPrompt,
|
|
289
|
+
cwd: projectRoot
|
|
290
|
+
});
|
|
291
|
+
} else {
|
|
292
|
+
execFileSync("xclip", ["-selection", "clipboard"], {
|
|
293
|
+
input: handoffPrompt,
|
|
294
|
+
cwd: projectRoot
|
|
295
|
+
});
|
|
296
|
+
}
|
|
264
297
|
console.log("\n\u2705 Handoff prompt copied to clipboard!");
|
|
265
298
|
} catch (err) {
|
|
266
299
|
console.log("\n\u26A0\uFE0F Could not copy to clipboard");
|
|
@@ -290,11 +323,25 @@ Generated by stackmemory handoff at ${timestamp}
|
|
|
290
323
|
console.log("\u{1F6E1}\uFE0F StackMemory Auto-Handoff");
|
|
291
324
|
console.log("\u2500".repeat(50));
|
|
292
325
|
if (options.command) {
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
326
|
+
const commandSchema = z.string().min(1, "Command cannot be empty").max(200, "Command too long").regex(/^[a-zA-Z0-9\s\-_./:]+$/, "Command contains invalid characters").refine((cmd2) => !cmd2.includes(";"), 'Command cannot contain ";"').refine((cmd2) => !cmd2.includes("&"), 'Command cannot contain "&"').refine((cmd2) => !cmd2.includes("|"), 'Command cannot contain "|"').refine((cmd2) => !cmd2.includes("$"), 'Command cannot contain "$"').refine((cmd2) => !cmd2.includes("`"), 'Command cannot contain "`"');
|
|
327
|
+
try {
|
|
328
|
+
const validatedCommand = commandSchema.parse(options.command);
|
|
329
|
+
console.log(`Wrapping command: ${validatedCommand}`);
|
|
330
|
+
execFileSync(scriptPath, [validatedCommand], {
|
|
331
|
+
stdio: "inherit",
|
|
332
|
+
env: { ...process.env, AUTO_CAPTURE_ON_EXIT: "true" }
|
|
333
|
+
});
|
|
334
|
+
} catch (validationError) {
|
|
335
|
+
if (validationError instanceof z.ZodError) {
|
|
336
|
+
console.error("\u274C Invalid command:");
|
|
337
|
+
validationError.errors.forEach((err) => {
|
|
338
|
+
console.error(` ${err.message}`);
|
|
339
|
+
});
|
|
340
|
+
} else {
|
|
341
|
+
console.error("\u274C Failed to execute command:", validationError.message);
|
|
342
|
+
}
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
298
345
|
} else {
|
|
299
346
|
console.log("To enable auto-handoff for your current session:");
|
|
300
347
|
console.log("");
|
|
@@ -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 } from 'child_process';\nimport { existsSync, readFileSync, writeFileSync } from 'fs';\nimport { join } from 'path';\nimport Database from 'better-sqlite3';\nimport { FrameManager } from '../../core/context/frame-manager.js';\nimport { PebblesTaskStore } from '../../features/tasks/pebbles-task-store.js';\nimport { logger } from '../../core/monitoring/logger.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\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 .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 (err: unknown) {\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 const commitMessage =\n options.message ||\n `chore: handoff checkpoint on ${currentBranch}`;\n\n // Commit\n execSync(`git commit -m \"${commitMessage}\"`, { cwd: projectRoot });\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 PebblesTaskStore(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 (err: unknown) {\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 const timestamp = new Date().toISOString();\n const 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\n // 7. Save handoff prompt\n const handoffPath = join(\n projectRoot,\n '.stackmemory',\n 'last-handoff.md'\n );\n writeFileSync(handoffPath, handoffPrompt);\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 const copyCommand =\n process.platform === 'darwin'\n ? 'pbcopy'\n : process.platform === 'win32'\n ? 'clip'\n : 'xclip -selection clipboard';\n\n execSync(copyCommand, {\n input: handoffPrompt,\n cwd: projectRoot,\n });\n\n console.log('\\n\u2705 Handoff prompt copied to clipboard!');\n } catch (err: unknown) {\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 (err: unknown) {\n // Not a git repo\n }\n\n // Copy to clipboard unless disabled\n if (options.copy !== false) {\n try {\n const copyCommand =\n process.platform === 'darwin'\n ? 'pbcopy'\n : process.platform === 'win32'\n ? 'clip'\n : 'xclip -selection clipboard';\n\n execSync(copyCommand, {\n input: handoffPrompt,\n cwd: projectRoot,\n });\n\n console.log('\\n\u2705 Handoff prompt copied to clipboard!');\n } catch (err: unknown) {\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 // Wrap specific command\n console.log(`Wrapping command: ${options.command}`);\n execSync(`${scriptPath} ${options.command}`, {\n stdio: 'inherit',\n env: { ...process.env, AUTO_CAPTURE_ON_EXIT: 'true' },\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
|
-
"mappings": "AAIA,SAAS,eAAe;AACxB,SAAS,
|
|
6
|
-
"names": []
|
|
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 { existsSync, readFileSync, writeFileSync } from 'fs';\nimport { join } from 'path';\nimport Database from 'better-sqlite3';\nimport shellEscape from 'shell-escape';\nimport { z } from 'zod';\nimport { FrameManager } from '../../core/context/frame-manager.js';\nimport { PebblesTaskStore } from '../../features/tasks/pebbles-task-store.js';\nimport { logger } from '../../core/monitoring/logger.js';\n\n// Input validation schemas \nconst CommitMessageSchema = z.string()\n .min(1, 'Commit message cannot be empty')\n .max(200, 'Commit message too long')\n .regex(/^[a-zA-Z0-9\\s\\-_.,:()\\/\\[\\]]+$/, 'Commit message contains invalid characters')\n .refine(msg => !msg.includes('\\n'), 'Commit message cannot contain newlines')\n .refine(msg => !msg.includes('\"'), 'Commit message cannot contain double quotes')\n .refine(msg => !msg.includes('`'), 'Commit message cannot contain backticks');\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\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 .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 (err: unknown) {\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('\u274C Invalid commit message:', (validationError as Error).message);\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 PebblesTaskStore(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 (err: unknown) {\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 const timestamp = new Date().toISOString();\n const 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\n // 7. Save handoff prompt\n const handoffPath = join(\n projectRoot,\n '.stackmemory',\n 'last-handoff.md'\n );\n writeFileSync(handoffPath, handoffPrompt);\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 (err: unknown) {\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 (err: unknown) {\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 (err: unknown) {\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.string()\n .min(1, 'Command cannot be empty')\n .max(200, 'Command too long')\n .regex(/^[a-zA-Z0-9\\s\\-_./:]+$/, 'Command contains invalid characters')\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('\u274C Failed to execute command:', (validationError as Error).message);\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
|
+
"mappings": "AAIA,SAAS,eAAe;AACxB,SAAS,UAAU,oBAAoB;AACvC,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,YAAY;AACrB,OAAO,cAAc;AAErB,SAAS,SAAS;AAClB,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,SAAS,cAAc;AAGvB,MAAM,sBAAsB,EAAE,OAAO,EAClC,IAAI,GAAG,gCAAgC,EACvC,IAAI,KAAK,yBAAyB,EAClC,MAAM,kCAAkC,4CAA4C,EACpF,OAAO,SAAO,CAAC,IAAI,SAAS,IAAI,GAAG,wCAAwC,EAC3E,OAAO,SAAO,CAAC,IAAI,SAAS,GAAG,GAAG,6CAA6C,EAC/E,OAAO,SAAO,CAAC,IAAI,SAAS,GAAG,GAAG,yC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AAE;AACd,cAAQ,IAAI,sBAAsB;AAClC,cAAQ,IAAI,OAAO,UAAU,SAAS;AACtC,cAAQ,IAAI,OAAO,UAAU,cAAc;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
|
+
"names": ["cmd"]
|
|
7
7
|
}
|
|
@@ -4,7 +4,7 @@ import chalk from "chalk";
|
|
|
4
4
|
import { homedir } from "os";
|
|
5
5
|
import { join } from "path";
|
|
6
6
|
import { existsSync, mkdirSync, writeFileSync } from "fs";
|
|
7
|
-
import {
|
|
7
|
+
import { execFileSync } from "child_process";
|
|
8
8
|
import { WorktreeManager } from "../../core/worktree/worktree-manager.js";
|
|
9
9
|
import { ProjectManager } from "../../core/projects/project-manager.js";
|
|
10
10
|
import { logger } from "../../core/monitoring/logger.js";
|
|
@@ -327,9 +327,9 @@ fi
|
|
|
327
327
|
exec stackmemory "$@"
|
|
328
328
|
`;
|
|
329
329
|
writeFileSync(sourcePath, wrapperScript);
|
|
330
|
-
|
|
330
|
+
execFileSync("chmod", ["+x", sourcePath]);
|
|
331
331
|
if (!existsSync(binPath)) {
|
|
332
|
-
|
|
332
|
+
execFileSync("ln", ["-s", sourcePath, binPath]);
|
|
333
333
|
console.log(chalk.green(" \u2713 Created claude-sm command"));
|
|
334
334
|
}
|
|
335
335
|
} catch (error) {
|