@stackmemoryai/stackmemory 0.5.39 ā 0.5.40
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.
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import { fileURLToPath as __fileURLToPath } from 'url';
|
|
2
|
+
import { dirname as __pathDirname } from 'path';
|
|
3
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
4
|
+
const __dirname = __pathDirname(__filename);
|
|
5
|
+
import { Command } from "commander";
|
|
6
|
+
import chalk from "chalk";
|
|
7
|
+
import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs";
|
|
8
|
+
import { join } from "path";
|
|
9
|
+
import { homedir } from "os";
|
|
10
|
+
import { execSync } from "child_process";
|
|
11
|
+
const CLAUDE_DIR = join(homedir(), ".claude");
|
|
12
|
+
const CLAUDE_CONFIG_FILE = join(CLAUDE_DIR, "config.json");
|
|
13
|
+
const MCP_CONFIG_FILE = join(CLAUDE_DIR, "stackmemory-mcp.json");
|
|
14
|
+
const HOOKS_JSON = join(CLAUDE_DIR, "hooks.json");
|
|
15
|
+
function createSetupMCPCommand() {
|
|
16
|
+
return new Command("setup-mcp").description("Auto-configure Claude Code MCP integration").option("--dry-run", "Show what would be configured without making changes").option("--reset", "Reset MCP configuration to defaults").action(async (options) => {
|
|
17
|
+
console.log(chalk.cyan("\nStackMemory MCP Setup\n"));
|
|
18
|
+
if (options.dryRun) {
|
|
19
|
+
console.log(chalk.yellow("[DRY RUN] No changes will be made.\n"));
|
|
20
|
+
}
|
|
21
|
+
if (!existsSync(CLAUDE_DIR)) {
|
|
22
|
+
if (options.dryRun) {
|
|
23
|
+
console.log(chalk.gray(`Would create: ${CLAUDE_DIR}`));
|
|
24
|
+
} else {
|
|
25
|
+
mkdirSync(CLAUDE_DIR, { recursive: true });
|
|
26
|
+
console.log(chalk.green("[OK]") + " Created ~/.claude directory");
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const mcpConfig = {
|
|
30
|
+
mcpServers: {
|
|
31
|
+
stackmemory: {
|
|
32
|
+
command: "stackmemory",
|
|
33
|
+
args: ["mcp-server"],
|
|
34
|
+
env: {
|
|
35
|
+
NODE_ENV: "production"
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
if (options.dryRun) {
|
|
41
|
+
console.log(
|
|
42
|
+
chalk.gray(`Would write MCP config to: ${MCP_CONFIG_FILE}`)
|
|
43
|
+
);
|
|
44
|
+
console.log(chalk.gray(JSON.stringify(mcpConfig, null, 2)));
|
|
45
|
+
} else {
|
|
46
|
+
writeFileSync(MCP_CONFIG_FILE, JSON.stringify(mcpConfig, null, 2));
|
|
47
|
+
console.log(chalk.green("[OK]") + " Created MCP server configuration");
|
|
48
|
+
}
|
|
49
|
+
let claudeConfig = {};
|
|
50
|
+
if (existsSync(CLAUDE_CONFIG_FILE)) {
|
|
51
|
+
try {
|
|
52
|
+
claudeConfig = JSON.parse(readFileSync(CLAUDE_CONFIG_FILE, "utf8"));
|
|
53
|
+
} catch {
|
|
54
|
+
console.log(
|
|
55
|
+
chalk.yellow("[WARN]") + " Could not parse existing config.json, creating new"
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (!claudeConfig.mcp) {
|
|
60
|
+
claudeConfig.mcp = {};
|
|
61
|
+
}
|
|
62
|
+
const mcp = claudeConfig.mcp;
|
|
63
|
+
if (!mcp.configFiles) {
|
|
64
|
+
mcp.configFiles = [];
|
|
65
|
+
}
|
|
66
|
+
const configFiles = mcp.configFiles;
|
|
67
|
+
if (!configFiles.includes(MCP_CONFIG_FILE)) {
|
|
68
|
+
configFiles.push(MCP_CONFIG_FILE);
|
|
69
|
+
}
|
|
70
|
+
if (options.dryRun) {
|
|
71
|
+
console.log(chalk.gray(`Would update: ${CLAUDE_CONFIG_FILE}`));
|
|
72
|
+
} else {
|
|
73
|
+
writeFileSync(
|
|
74
|
+
CLAUDE_CONFIG_FILE,
|
|
75
|
+
JSON.stringify(claudeConfig, null, 2)
|
|
76
|
+
);
|
|
77
|
+
console.log(chalk.green("[OK]") + " Updated Claude config.json");
|
|
78
|
+
}
|
|
79
|
+
console.log(chalk.cyan("\nValidating configuration..."));
|
|
80
|
+
try {
|
|
81
|
+
execSync("stackmemory --version", { stdio: "pipe" });
|
|
82
|
+
console.log(chalk.green("[OK]") + " stackmemory CLI is installed");
|
|
83
|
+
} catch {
|
|
84
|
+
console.log(chalk.yellow("[WARN]") + " stackmemory CLI not in PATH");
|
|
85
|
+
console.log(chalk.gray(" You may need to restart your terminal"));
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
execSync("claude --version", { stdio: "pipe" });
|
|
89
|
+
console.log(chalk.green("[OK]") + " Claude Code is installed");
|
|
90
|
+
} catch {
|
|
91
|
+
console.log(chalk.yellow("[WARN]") + " Claude Code not found");
|
|
92
|
+
console.log(chalk.gray(" Install from: https://claude.ai/code"));
|
|
93
|
+
}
|
|
94
|
+
if (!options.dryRun) {
|
|
95
|
+
console.log(chalk.green("\nMCP setup complete!"));
|
|
96
|
+
console.log(chalk.cyan("\nNext steps:"));
|
|
97
|
+
console.log(chalk.white(" 1. Restart Claude Code"));
|
|
98
|
+
console.log(
|
|
99
|
+
chalk.white(
|
|
100
|
+
" 2. The StackMemory MCP tools will be available automatically"
|
|
101
|
+
)
|
|
102
|
+
);
|
|
103
|
+
console.log(
|
|
104
|
+
chalk.gray(
|
|
105
|
+
'\nTo verify: Run "stackmemory doctor" to check all integrations'
|
|
106
|
+
)
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
function createDoctorCommand() {
|
|
112
|
+
return new Command("doctor").description("Diagnose StackMemory configuration and common issues").option("--fix", "Attempt to automatically fix issues").action(async (options) => {
|
|
113
|
+
console.log(chalk.cyan("\nStackMemory Doctor\n"));
|
|
114
|
+
console.log(chalk.gray("Checking configuration and dependencies...\n"));
|
|
115
|
+
const results = [];
|
|
116
|
+
const projectDir = join(process.cwd(), ".stackmemory");
|
|
117
|
+
const dbPath = join(projectDir, "context.db");
|
|
118
|
+
if (existsSync(dbPath)) {
|
|
119
|
+
results.push({
|
|
120
|
+
name: "Project Initialization",
|
|
121
|
+
status: "ok",
|
|
122
|
+
message: "StackMemory is initialized in this project"
|
|
123
|
+
});
|
|
124
|
+
} else if (existsSync(projectDir)) {
|
|
125
|
+
results.push({
|
|
126
|
+
name: "Project Initialization",
|
|
127
|
+
status: "warn",
|
|
128
|
+
message: ".stackmemory directory exists but database not found",
|
|
129
|
+
fix: "Run: stackmemory init"
|
|
130
|
+
});
|
|
131
|
+
} else {
|
|
132
|
+
results.push({
|
|
133
|
+
name: "Project Initialization",
|
|
134
|
+
status: "error",
|
|
135
|
+
message: "StackMemory not initialized in this project",
|
|
136
|
+
fix: "Run: stackmemory init"
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
if (existsSync(dbPath)) {
|
|
140
|
+
try {
|
|
141
|
+
const Database = (await import("better-sqlite3")).default;
|
|
142
|
+
const db = new Database(dbPath, { readonly: true });
|
|
143
|
+
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all();
|
|
144
|
+
db.close();
|
|
145
|
+
const hasFrames = tables.some((t) => t.name === "frames");
|
|
146
|
+
if (hasFrames) {
|
|
147
|
+
results.push({
|
|
148
|
+
name: "Database Integrity",
|
|
149
|
+
status: "ok",
|
|
150
|
+
message: `Database has ${tables.length} tables`
|
|
151
|
+
});
|
|
152
|
+
} else {
|
|
153
|
+
results.push({
|
|
154
|
+
name: "Database Integrity",
|
|
155
|
+
status: "warn",
|
|
156
|
+
message: "Database exists but missing expected tables",
|
|
157
|
+
fix: "Run: stackmemory init --interactive"
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
} catch (error) {
|
|
161
|
+
results.push({
|
|
162
|
+
name: "Database Integrity",
|
|
163
|
+
status: "error",
|
|
164
|
+
message: `Database error: ${error.message}`,
|
|
165
|
+
fix: "Remove .stackmemory/context.db and run: stackmemory init"
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (existsSync(MCP_CONFIG_FILE)) {
|
|
170
|
+
try {
|
|
171
|
+
const config = JSON.parse(readFileSync(MCP_CONFIG_FILE, "utf8"));
|
|
172
|
+
if (config.mcpServers?.stackmemory) {
|
|
173
|
+
results.push({
|
|
174
|
+
name: "MCP Configuration",
|
|
175
|
+
status: "ok",
|
|
176
|
+
message: "MCP server configured"
|
|
177
|
+
});
|
|
178
|
+
} else {
|
|
179
|
+
results.push({
|
|
180
|
+
name: "MCP Configuration",
|
|
181
|
+
status: "warn",
|
|
182
|
+
message: "MCP config file exists but stackmemory server not configured",
|
|
183
|
+
fix: "Run: stackmemory setup-mcp"
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
} catch {
|
|
187
|
+
results.push({
|
|
188
|
+
name: "MCP Configuration",
|
|
189
|
+
status: "error",
|
|
190
|
+
message: "Invalid MCP configuration file",
|
|
191
|
+
fix: "Run: stackmemory setup-mcp --reset"
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
} else {
|
|
195
|
+
results.push({
|
|
196
|
+
name: "MCP Configuration",
|
|
197
|
+
status: "warn",
|
|
198
|
+
message: "MCP not configured for Claude Code",
|
|
199
|
+
fix: "Run: stackmemory setup-mcp"
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
if (existsSync(HOOKS_JSON)) {
|
|
203
|
+
try {
|
|
204
|
+
const hooks = JSON.parse(readFileSync(HOOKS_JSON, "utf8"));
|
|
205
|
+
const hasTraceHook = !!hooks["tool-use-approval"];
|
|
206
|
+
if (hasTraceHook) {
|
|
207
|
+
results.push({
|
|
208
|
+
name: "Claude Hooks",
|
|
209
|
+
status: "ok",
|
|
210
|
+
message: "Tool tracing hook installed"
|
|
211
|
+
});
|
|
212
|
+
} else {
|
|
213
|
+
results.push({
|
|
214
|
+
name: "Claude Hooks",
|
|
215
|
+
status: "warn",
|
|
216
|
+
message: "Hooks file exists but tracing not configured",
|
|
217
|
+
fix: "Run: stackmemory hooks install"
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
} catch {
|
|
221
|
+
results.push({
|
|
222
|
+
name: "Claude Hooks",
|
|
223
|
+
status: "warn",
|
|
224
|
+
message: "Could not read hooks.json"
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
} else {
|
|
228
|
+
results.push({
|
|
229
|
+
name: "Claude Hooks",
|
|
230
|
+
status: "warn",
|
|
231
|
+
message: "Claude hooks not installed (optional)",
|
|
232
|
+
fix: "Run: stackmemory hooks install"
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
const envChecks = [
|
|
236
|
+
{ key: "LINEAR_API_KEY", name: "Linear API Key", optional: true },
|
|
237
|
+
{ key: "TWILIO_ACCOUNT_SID", name: "Twilio Account", optional: true }
|
|
238
|
+
];
|
|
239
|
+
for (const check of envChecks) {
|
|
240
|
+
const value = process.env[check.key];
|
|
241
|
+
if (value) {
|
|
242
|
+
results.push({
|
|
243
|
+
name: check.name,
|
|
244
|
+
status: "ok",
|
|
245
|
+
message: "Environment variable set"
|
|
246
|
+
});
|
|
247
|
+
} else if (!check.optional) {
|
|
248
|
+
results.push({
|
|
249
|
+
name: check.name,
|
|
250
|
+
status: "error",
|
|
251
|
+
message: "Required environment variable not set",
|
|
252
|
+
fix: `Set ${check.key} in your .env file`
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
const homeStackmemory = join(homedir(), ".stackmemory");
|
|
257
|
+
if (existsSync(homeStackmemory)) {
|
|
258
|
+
try {
|
|
259
|
+
const testFile = join(homeStackmemory, ".write-test");
|
|
260
|
+
writeFileSync(testFile, "test");
|
|
261
|
+
const { unlinkSync } = await import("fs");
|
|
262
|
+
unlinkSync(testFile);
|
|
263
|
+
results.push({
|
|
264
|
+
name: "File Permissions",
|
|
265
|
+
status: "ok",
|
|
266
|
+
message: "~/.stackmemory is writable"
|
|
267
|
+
});
|
|
268
|
+
} catch {
|
|
269
|
+
results.push({
|
|
270
|
+
name: "File Permissions",
|
|
271
|
+
status: "error",
|
|
272
|
+
message: "~/.stackmemory is not writable",
|
|
273
|
+
fix: "Run: chmod 700 ~/.stackmemory"
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
let hasErrors = false;
|
|
278
|
+
let hasWarnings = false;
|
|
279
|
+
for (const result of results) {
|
|
280
|
+
const icon = result.status === "ok" ? chalk.green("[OK]") : result.status === "warn" ? chalk.yellow("[WARN]") : chalk.red("[ERROR]");
|
|
281
|
+
console.log(`${icon} ${result.name}`);
|
|
282
|
+
console.log(chalk.gray(` ${result.message}`));
|
|
283
|
+
if (result.fix) {
|
|
284
|
+
console.log(chalk.cyan(` Fix: ${result.fix}`));
|
|
285
|
+
if (options.fix && result.status !== "ok") {
|
|
286
|
+
if (result.fix.includes("stackmemory setup-mcp")) {
|
|
287
|
+
console.log(chalk.gray(" Attempting auto-fix..."));
|
|
288
|
+
try {
|
|
289
|
+
execSync("stackmemory setup-mcp", { stdio: "inherit" });
|
|
290
|
+
} catch {
|
|
291
|
+
console.log(chalk.red(" Auto-fix failed"));
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
if (result.status === "error") hasErrors = true;
|
|
297
|
+
if (result.status === "warn") hasWarnings = true;
|
|
298
|
+
}
|
|
299
|
+
console.log("");
|
|
300
|
+
if (hasErrors) {
|
|
301
|
+
console.log(
|
|
302
|
+
chalk.red("Some issues need attention. Run suggested fixes above.")
|
|
303
|
+
);
|
|
304
|
+
process.exit(1);
|
|
305
|
+
} else if (hasWarnings) {
|
|
306
|
+
console.log(
|
|
307
|
+
chalk.yellow(
|
|
308
|
+
"StackMemory is working but some optional features are not configured."
|
|
309
|
+
)
|
|
310
|
+
);
|
|
311
|
+
} else {
|
|
312
|
+
console.log(
|
|
313
|
+
chalk.green("All checks passed! StackMemory is properly configured.")
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
function registerSetupCommands(program) {
|
|
319
|
+
program.addCommand(createSetupMCPCommand());
|
|
320
|
+
program.addCommand(createDoctorCommand());
|
|
321
|
+
}
|
|
322
|
+
export {
|
|
323
|
+
createDoctorCommand,
|
|
324
|
+
createSetupMCPCommand,
|
|
325
|
+
registerSetupCommands
|
|
326
|
+
};
|
|
327
|
+
//# sourceMappingURL=setup.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/cli/commands/setup.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Setup commands for StackMemory onboarding\n * - setup-mcp: Auto-configure Claude Code MCP integration\n * - doctor: Diagnose common issues\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { execSync } from 'child_process';\n\n// Claude config paths\nconst CLAUDE_DIR = join(homedir(), '.claude');\nconst CLAUDE_CONFIG_FILE = join(CLAUDE_DIR, 'config.json');\nconst MCP_CONFIG_FILE = join(CLAUDE_DIR, 'stackmemory-mcp.json');\nconst HOOKS_JSON = join(CLAUDE_DIR, 'hooks.json');\n\ninterface DiagnosticResult {\n name: string;\n status: 'ok' | 'warn' | 'error';\n message: string;\n fix?: string;\n}\n\n/**\n * Create setup-mcp command\n */\nexport function createSetupMCPCommand(): Command {\n return new Command('setup-mcp')\n .description('Auto-configure Claude Code MCP integration')\n .option('--dry-run', 'Show what would be configured without making changes')\n .option('--reset', 'Reset MCP configuration to defaults')\n .action(async (options) => {\n console.log(chalk.cyan('\\nStackMemory MCP Setup\\n'));\n\n if (options.dryRun) {\n console.log(chalk.yellow('[DRY RUN] No changes will be made.\\n'));\n }\n\n // Step 1: Ensure Claude directory exists\n if (!existsSync(CLAUDE_DIR)) {\n if (options.dryRun) {\n console.log(chalk.gray(`Would create: ${CLAUDE_DIR}`));\n } else {\n mkdirSync(CLAUDE_DIR, { recursive: true });\n console.log(chalk.green('[OK]') + ' Created ~/.claude directory');\n }\n }\n\n // Step 2: Create MCP server configuration\n const mcpConfig = {\n mcpServers: {\n stackmemory: {\n command: 'stackmemory',\n args: ['mcp-server'],\n env: {\n NODE_ENV: 'production',\n },\n },\n },\n };\n\n if (options.dryRun) {\n console.log(\n chalk.gray(`Would write MCP config to: ${MCP_CONFIG_FILE}`)\n );\n console.log(chalk.gray(JSON.stringify(mcpConfig, null, 2)));\n } else {\n writeFileSync(MCP_CONFIG_FILE, JSON.stringify(mcpConfig, null, 2));\n console.log(chalk.green('[OK]') + ' Created MCP server configuration');\n }\n\n // Step 3: Update Claude config.json to reference MCP config\n let claudeConfig: Record<string, unknown> = {};\n if (existsSync(CLAUDE_CONFIG_FILE)) {\n try {\n claudeConfig = JSON.parse(readFileSync(CLAUDE_CONFIG_FILE, 'utf8'));\n } catch {\n console.log(\n chalk.yellow('[WARN]') +\n ' Could not parse existing config.json, creating new'\n );\n }\n }\n\n // Ensure mcp.configFiles array includes our config\n if (!claudeConfig.mcp) {\n claudeConfig.mcp = {};\n }\n const mcp = claudeConfig.mcp as Record<string, unknown>;\n if (!mcp.configFiles) {\n mcp.configFiles = [];\n }\n const configFiles = mcp.configFiles as string[];\n if (!configFiles.includes(MCP_CONFIG_FILE)) {\n configFiles.push(MCP_CONFIG_FILE);\n }\n\n if (options.dryRun) {\n console.log(chalk.gray(`Would update: ${CLAUDE_CONFIG_FILE}`));\n } else {\n writeFileSync(\n CLAUDE_CONFIG_FILE,\n JSON.stringify(claudeConfig, null, 2)\n );\n console.log(chalk.green('[OK]') + ' Updated Claude config.json');\n }\n\n // Step 4: Validate configuration\n console.log(chalk.cyan('\\nValidating configuration...'));\n\n // Check stackmemory command is available\n try {\n execSync('stackmemory --version', { stdio: 'pipe' });\n console.log(chalk.green('[OK]') + ' stackmemory CLI is installed');\n } catch {\n console.log(chalk.yellow('[WARN]') + ' stackmemory CLI not in PATH');\n console.log(chalk.gray(' You may need to restart your terminal'));\n }\n\n // Check Claude Code is available\n try {\n execSync('claude --version', { stdio: 'pipe' });\n console.log(chalk.green('[OK]') + ' Claude Code is installed');\n } catch {\n console.log(chalk.yellow('[WARN]') + ' Claude Code not found');\n console.log(chalk.gray(' Install from: https://claude.ai/code'));\n }\n\n // Final instructions\n if (!options.dryRun) {\n console.log(chalk.green('\\nMCP setup complete!'));\n console.log(chalk.cyan('\\nNext steps:'));\n console.log(chalk.white(' 1. Restart Claude Code'));\n console.log(\n chalk.white(\n ' 2. The StackMemory MCP tools will be available automatically'\n )\n );\n console.log(\n chalk.gray(\n '\\nTo verify: Run \"stackmemory doctor\" to check all integrations'\n )\n );\n }\n });\n}\n\n/**\n * Create doctor command for diagnostics\n */\nexport function createDoctorCommand(): Command {\n return new Command('doctor')\n .description('Diagnose StackMemory configuration and common issues')\n .option('--fix', 'Attempt to automatically fix issues')\n .action(async (options) => {\n console.log(chalk.cyan('\\nStackMemory Doctor\\n'));\n console.log(chalk.gray('Checking configuration and dependencies...\\n'));\n\n const results: DiagnosticResult[] = [];\n\n // 1. Check project initialization\n const projectDir = join(process.cwd(), '.stackmemory');\n const dbPath = join(projectDir, 'context.db');\n if (existsSync(dbPath)) {\n results.push({\n name: 'Project Initialization',\n status: 'ok',\n message: 'StackMemory is initialized in this project',\n });\n } else if (existsSync(projectDir)) {\n results.push({\n name: 'Project Initialization',\n status: 'warn',\n message: '.stackmemory directory exists but database not found',\n fix: 'Run: stackmemory init',\n });\n } else {\n results.push({\n name: 'Project Initialization',\n status: 'error',\n message: 'StackMemory not initialized in this project',\n fix: 'Run: stackmemory init',\n });\n }\n\n // 2. Check database integrity\n if (existsSync(dbPath)) {\n try {\n const Database = (await import('better-sqlite3')).default;\n const db = new Database(dbPath, { readonly: true });\n const tables = db\n .prepare(\"SELECT name FROM sqlite_master WHERE type='table'\")\n .all() as { name: string }[];\n db.close();\n\n const hasFrames = tables.some((t) => t.name === 'frames');\n if (hasFrames) {\n results.push({\n name: 'Database Integrity',\n status: 'ok',\n message: `Database has ${tables.length} tables`,\n });\n } else {\n results.push({\n name: 'Database Integrity',\n status: 'warn',\n message: 'Database exists but missing expected tables',\n fix: 'Run: stackmemory init --interactive',\n });\n }\n } catch (error) {\n results.push({\n name: 'Database Integrity',\n status: 'error',\n message: `Database error: ${(error as Error).message}`,\n fix: 'Remove .stackmemory/context.db and run: stackmemory init',\n });\n }\n }\n\n // 3. Check MCP configuration\n if (existsSync(MCP_CONFIG_FILE)) {\n try {\n const config = JSON.parse(readFileSync(MCP_CONFIG_FILE, 'utf8'));\n if (config.mcpServers?.stackmemory) {\n results.push({\n name: 'MCP Configuration',\n status: 'ok',\n message: 'MCP server configured',\n });\n } else {\n results.push({\n name: 'MCP Configuration',\n status: 'warn',\n message:\n 'MCP config file exists but stackmemory server not configured',\n fix: 'Run: stackmemory setup-mcp',\n });\n }\n } catch {\n results.push({\n name: 'MCP Configuration',\n status: 'error',\n message: 'Invalid MCP configuration file',\n fix: 'Run: stackmemory setup-mcp --reset',\n });\n }\n } else {\n results.push({\n name: 'MCP Configuration',\n status: 'warn',\n message: 'MCP not configured for Claude Code',\n fix: 'Run: stackmemory setup-mcp',\n });\n }\n\n // 4. Check Claude hooks\n if (existsSync(HOOKS_JSON)) {\n try {\n const hooks = JSON.parse(readFileSync(HOOKS_JSON, 'utf8'));\n const hasTraceHook = !!hooks['tool-use-approval'];\n if (hasTraceHook) {\n results.push({\n name: 'Claude Hooks',\n status: 'ok',\n message: 'Tool tracing hook installed',\n });\n } else {\n results.push({\n name: 'Claude Hooks',\n status: 'warn',\n message: 'Hooks file exists but tracing not configured',\n fix: 'Run: stackmemory hooks install',\n });\n }\n } catch {\n results.push({\n name: 'Claude Hooks',\n status: 'warn',\n message: 'Could not read hooks.json',\n });\n }\n } else {\n results.push({\n name: 'Claude Hooks',\n status: 'warn',\n message: 'Claude hooks not installed (optional)',\n fix: 'Run: stackmemory hooks install',\n });\n }\n\n // 5. Check environment variables\n const envChecks = [\n { key: 'LINEAR_API_KEY', name: 'Linear API Key', optional: true },\n { key: 'TWILIO_ACCOUNT_SID', name: 'Twilio Account', optional: true },\n ];\n\n for (const check of envChecks) {\n const value = process.env[check.key];\n if (value) {\n results.push({\n name: check.name,\n status: 'ok',\n message: 'Environment variable set',\n });\n } else if (!check.optional) {\n results.push({\n name: check.name,\n status: 'error',\n message: 'Required environment variable not set',\n fix: `Set ${check.key} in your .env file`,\n });\n }\n // Skip optional env vars that aren't set\n }\n\n // 6. Check file permissions\n const homeStackmemory = join(homedir(), '.stackmemory');\n if (existsSync(homeStackmemory)) {\n try {\n const testFile = join(homeStackmemory, '.write-test');\n writeFileSync(testFile, 'test');\n const { unlinkSync } = await import('fs');\n unlinkSync(testFile);\n results.push({\n name: 'File Permissions',\n status: 'ok',\n message: '~/.stackmemory is writable',\n });\n } catch {\n results.push({\n name: 'File Permissions',\n status: 'error',\n message: '~/.stackmemory is not writable',\n fix: 'Run: chmod 700 ~/.stackmemory',\n });\n }\n }\n\n // Display results\n let hasErrors = false;\n let hasWarnings = false;\n\n for (const result of results) {\n const icon =\n result.status === 'ok'\n ? chalk.green('[OK]')\n : result.status === 'warn'\n ? chalk.yellow('[WARN]')\n : chalk.red('[ERROR]');\n\n console.log(`${icon} ${result.name}`);\n console.log(chalk.gray(` ${result.message}`));\n\n if (result.fix) {\n console.log(chalk.cyan(` Fix: ${result.fix}`));\n\n if (options.fix && result.status !== 'ok') {\n // Auto-fix logic for specific issues\n if (result.fix.includes('stackmemory setup-mcp')) {\n console.log(chalk.gray(' Attempting auto-fix...'));\n try {\n execSync('stackmemory setup-mcp', { stdio: 'inherit' });\n } catch {\n console.log(chalk.red(' Auto-fix failed'));\n }\n }\n }\n }\n\n if (result.status === 'error') hasErrors = true;\n if (result.status === 'warn') hasWarnings = true;\n }\n\n // Summary\n console.log('');\n if (hasErrors) {\n console.log(\n chalk.red('Some issues need attention. Run suggested fixes above.')\n );\n process.exit(1);\n } else if (hasWarnings) {\n console.log(\n chalk.yellow(\n 'StackMemory is working but some optional features are not configured.'\n )\n );\n } else {\n console.log(\n chalk.green('All checks passed! StackMemory is properly configured.')\n );\n }\n });\n}\n\n/**\n * Register setup commands\n */\nexport function registerSetupCommands(program: Command): void {\n program.addCommand(createSetupMCPCommand());\n program.addCommand(createDoctorCommand());\n}\n"],
|
|
5
|
+
"mappings": ";;;;AAMA,SAAS,eAAe;AACxB,OAAO,WAAW;AAClB,SAAS,YAAY,cAAc,eAAe,iBAAiB;AACnE,SAAS,YAAY;AACrB,SAAS,eAAe;AACxB,SAAS,gBAAgB;AAGzB,MAAM,aAAa,KAAK,QAAQ,GAAG,SAAS;AAC5C,MAAM,qBAAqB,KAAK,YAAY,aAAa;AACzD,MAAM,kBAAkB,KAAK,YAAY,sBAAsB;AAC/D,MAAM,aAAa,KAAK,YAAY,YAAY;AAYzC,SAAS,wBAAiC;AAC/C,SAAO,IAAI,QAAQ,WAAW,EAC3B,YAAY,4CAA4C,EACxD,OAAO,aAAa,sDAAsD,EAC1E,OAAO,WAAW,qCAAqC,EACvD,OAAO,OAAO,YAAY;AACzB,YAAQ,IAAI,MAAM,KAAK,2BAA2B,CAAC;AAEnD,QAAI,QAAQ,QAAQ;AAClB,cAAQ,IAAI,MAAM,OAAO,sCAAsC,CAAC;AAAA,IAClE;AAGA,QAAI,CAAC,WAAW,UAAU,GAAG;AAC3B,UAAI,QAAQ,QAAQ;AAClB,gBAAQ,IAAI,MAAM,KAAK,iBAAiB,UAAU,EAAE,CAAC;AAAA,MACvD,OAAO;AACL,kBAAU,YAAY,EAAE,WAAW,KAAK,CAAC;AACzC,gBAAQ,IAAI,MAAM,MAAM,MAAM,IAAI,8BAA8B;AAAA,MAClE;AAAA,IACF;AAGA,UAAM,YAAY;AAAA,MAChB,YAAY;AAAA,QACV,aAAa;AAAA,UACX,S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C;AACpD,gBAAI;AACF,uBAAS,yBAAyB,EAAE,OAAO,UAAU,CAAC;AAAA,YACxD,QAAQ;AACN,sBAAQ,IAAI,MAAM,IAAI,qBAAqB,CAAC;AAAA,YAC9C;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAEA,UAAI,OAAO,WAAW,QAAS,aAAY;AAC3C,UAAI,OAAO,WAAW,OAAQ,eAAc;AAAA,IAC9C;AAGA,YAAQ,IAAI,EAAE;AACd,QAAI,WAAW;AACb,cAAQ;AAAA,QACN,MAAM,IAAI,wDAAwD;AAAA,MACpE;AACA,cAAQ,KAAK,CAAC;AAAA,IAChB,WAAW,aAAa;AACtB,cAAQ;AAAA,QACN,MAAM;AAAA,UACJ;AAAA,QACF;AAAA,MACF;AAAA,IACF,OAAO;AACL,cAAQ;AAAA,QACN,MAAM,MAAM,wDAAwD;AAAA,MACtE;AAAA,IACF;AAAA,EACF,CAAC;AACL;AAKO,SAAS,sBAAsB,SAAwB;AAC5D,UAAQ,WAAW,sBAAsB,CAAC;AAC1C,UAAQ,WAAW,oBAAoB,CAAC;AAC1C;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/cli/index.js
CHANGED
|
@@ -50,17 +50,14 @@ import { createSettingsCommand } from "./commands/settings.js";
|
|
|
50
50
|
import { createRetrievalCommands } from "./commands/retrieval.js";
|
|
51
51
|
import { createDiscoveryCommands } from "./commands/discovery.js";
|
|
52
52
|
import { createModelCommand } from "./commands/model.js";
|
|
53
|
+
import { registerSetupCommands } from "./commands/setup.js";
|
|
53
54
|
import { ProjectManager } from "../core/projects/project-manager.js";
|
|
54
55
|
import Database from "better-sqlite3";
|
|
55
56
|
import { join } from "path";
|
|
56
57
|
import { existsSync, mkdirSync } from "fs";
|
|
57
58
|
import inquirer from "inquirer";
|
|
58
59
|
import chalk from "chalk";
|
|
59
|
-
import {
|
|
60
|
-
loadStorageConfig,
|
|
61
|
-
enableChromaDB,
|
|
62
|
-
getStorageModeDescription
|
|
63
|
-
} from "../core/config/storage-config.js";
|
|
60
|
+
import { enableChromaDB } from "../core/config/storage-config.js";
|
|
64
61
|
import { spawn } from "child_process";
|
|
65
62
|
import { homedir } from "os";
|
|
66
63
|
import { createRequire } from "module";
|
|
@@ -131,69 +128,77 @@ program.name("stackmemory").description(
|
|
|
131
128
|
"Lossless memory runtime for AI coding tools - organizes context as a call stack instead of linear chat logs, with team collaboration and infinite retention"
|
|
132
129
|
).version(VERSION);
|
|
133
130
|
program.command("init").description(
|
|
134
|
-
`Initialize StackMemory in current project
|
|
131
|
+
`Initialize StackMemory in current project (zero-config by default)
|
|
135
132
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
ChromaDB
|
|
139
|
-
).option("--
|
|
133
|
+
Options:
|
|
134
|
+
--interactive Ask configuration questions
|
|
135
|
+
--chromadb Enable ChromaDB semantic search (prompts for API key)`
|
|
136
|
+
).option("-i, --interactive", "Interactive mode with configuration prompts").option(
|
|
140
137
|
"--chromadb",
|
|
141
138
|
"Enable ChromaDB for semantic search (prompts for API key)"
|
|
142
|
-
).
|
|
139
|
+
).action(async (options) => {
|
|
143
140
|
try {
|
|
144
141
|
const projectRoot = process.cwd();
|
|
145
142
|
const dbDir = join(projectRoot, ".stackmemory");
|
|
143
|
+
const alreadyInit = existsSync(join(dbDir, "context.db"));
|
|
144
|
+
if (alreadyInit && !options.interactive) {
|
|
145
|
+
console.log(chalk.yellow("StackMemory already initialized."));
|
|
146
|
+
console.log(chalk.gray("Run with --interactive to reconfigure."));
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
146
149
|
if (!existsSync(dbDir)) {
|
|
147
150
|
mkdirSync(dbDir, { recursive: true });
|
|
148
151
|
}
|
|
149
|
-
|
|
150
|
-
const isFirstTimeSetup = !storageConfig.chromadb.enabled && storageConfig.mode === "sqlite";
|
|
151
|
-
if (options.sqlite || options.skipStoragePrompt) {
|
|
152
|
-
console.log(chalk.gray("Using SQLite-only storage mode."));
|
|
153
|
-
} else if (options.chromadb) {
|
|
152
|
+
if (options.chromadb) {
|
|
154
153
|
await promptAndEnableChromaDB();
|
|
155
|
-
} else if (
|
|
154
|
+
} else if (options.interactive && process.stdin.isTTY) {
|
|
156
155
|
console.log(chalk.cyan("\nStorage Configuration"));
|
|
157
|
-
console.log(
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
console.log(
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
console.log(chalk.gray(" - Semantic search across your context"));
|
|
164
|
-
console.log(chalk.gray(" - Cloud backup capability"));
|
|
165
|
-
console.log(chalk.gray(" - Requires ChromaDB API key\n"));
|
|
156
|
+
console.log(
|
|
157
|
+
chalk.gray("SQLite (default) is fast and requires no setup.")
|
|
158
|
+
);
|
|
159
|
+
console.log(
|
|
160
|
+
chalk.gray("ChromaDB adds semantic search but requires an API key.\n")
|
|
161
|
+
);
|
|
166
162
|
const { enableChroma } = await inquirer.prompt([
|
|
167
163
|
{
|
|
168
164
|
type: "confirm",
|
|
169
165
|
name: "enableChroma",
|
|
170
|
-
message: "Enable ChromaDB for semantic search?
|
|
166
|
+
message: "Enable ChromaDB for semantic search?",
|
|
171
167
|
default: false
|
|
172
168
|
}
|
|
173
169
|
]);
|
|
174
170
|
if (enableChroma) {
|
|
175
171
|
await promptAndEnableChromaDB();
|
|
176
|
-
} else {
|
|
177
|
-
console.log(chalk.gray("Using SQLite-only storage mode."));
|
|
178
172
|
}
|
|
179
173
|
}
|
|
180
174
|
const dbPath = join(dbDir, "context.db");
|
|
181
175
|
const db = new Database(dbPath);
|
|
182
176
|
new FrameManager(db, "cli-project");
|
|
183
177
|
logger.info("StackMemory initialized successfully", { projectRoot });
|
|
178
|
+
console.log(chalk.green("\n[OK] StackMemory initialized"));
|
|
179
|
+
console.log(chalk.gray(` Project: ${projectRoot}`));
|
|
180
|
+
console.log(chalk.gray(` Storage: SQLite (local)`));
|
|
181
|
+
console.log(chalk.cyan("\nNext steps:"));
|
|
182
|
+
console.log(
|
|
183
|
+
chalk.white(" 1. stackmemory setup-mcp") + chalk.gray(" # Configure Claude Code integration")
|
|
184
|
+
);
|
|
185
|
+
console.log(
|
|
186
|
+
chalk.white(" 2. stackmemory status") + chalk.gray(" # Check status")
|
|
187
|
+
);
|
|
184
188
|
console.log(
|
|
185
|
-
chalk.
|
|
186
|
-
projectRoot
|
|
189
|
+
chalk.white(" 3. stackmemory doctor") + chalk.gray(" # Diagnose issues")
|
|
187
190
|
);
|
|
188
|
-
storageConfig = loadStorageConfig();
|
|
189
|
-
console.log(chalk.gray(`Storage mode: ${getStorageModeDescription()}`));
|
|
190
191
|
db.close();
|
|
191
192
|
} catch (error) {
|
|
192
193
|
logger.error("Failed to initialize StackMemory", error);
|
|
194
|
+
console.error(chalk.red("\n[ERROR] Initialization failed"));
|
|
195
|
+
console.error(chalk.gray(` Reason: ${error.message}`));
|
|
193
196
|
console.error(
|
|
194
|
-
chalk.
|
|
195
|
-
|
|
197
|
+
chalk.gray(
|
|
198
|
+
" Fix: Ensure you have write permissions to the current directory"
|
|
199
|
+
)
|
|
196
200
|
);
|
|
201
|
+
console.error(chalk.gray(" Run: stackmemory doctor"));
|
|
197
202
|
process.exit(1);
|
|
198
203
|
}
|
|
199
204
|
});
|
|
@@ -517,6 +522,7 @@ if (isFeatureEnabled("whatsapp")) {
|
|
|
517
522
|
program.addCommand(createRetrievalCommands());
|
|
518
523
|
program.addCommand(createDiscoveryCommands());
|
|
519
524
|
program.addCommand(createModelCommand());
|
|
525
|
+
registerSetupCommands(program);
|
|
520
526
|
program.command("dashboard").description("Display monitoring dashboard in terminal").option("-w, --watch", "Auto-refresh dashboard").option("-i, --interval <seconds>", "Refresh interval in seconds", "5").action(async (options) => {
|
|
521
527
|
const { dashboardCommand } = await import("./commands/dashboard.js");
|
|
522
528
|
await dashboardCommand.handler(options);
|
package/dist/cli/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/cli/index.ts"],
|
|
4
|
-
"sourcesContent": ["#!/usr/bin/env node\n/**\n * StackMemory CLI\n * Command-line interface for StackMemory operations\n */\n\n// Set environment flag for CLI usage to skip async context bridge\nprocess.env['STACKMEMORY_CLI'] = 'true';\n\n// Load environment variables\nimport 'dotenv/config';\n\n// Initialize tracing system early\nimport { initializeTracing, trace } from '../core/trace/index.js';\ninitializeTracing();\n\nimport { program } from 'commander';\nimport { logger } from '../core/monitoring/logger.js';\nimport { FrameManager } from '../core/context/index.js';\nimport { sessionManager, FrameQueryMode } from '../core/session/index.js';\nimport { sharedContextLayer } from '../core/context/shared-context-layer.js';\nimport { UpdateChecker } from '../core/utils/update-checker.js';\nimport { ProgressTracker } from '../core/monitoring/progress-tracker.js';\nimport { registerProjectCommands } from './commands/projects.js';\nimport { createSessionCommands } from './commands/session.js';\nimport { isFeatureEnabled, isLocalOnly } from '../core/config/feature-flags.js';\nimport { registerWorktreeCommands } from './commands/worktree.js';\nimport { registerOnboardingCommand } from './commands/onboard.js';\nimport { createTaskCommands } from './commands/tasks.js';\nimport { createSearchCommand } from './commands/search.js';\nimport { createLogCommand } from './commands/log.js';\nimport { createContextCommands } from './commands/context.js';\nimport { createConfigCommand } from './commands/config.js';\nimport { createHandoffCommand } from './commands/handoff.js';\nimport {\n createDecisionCommand,\n createMemoryCommand,\n} from './commands/decision.js';\nimport { createSkillsCommand } from './commands/skills.js';\nimport { createTestCommand } from './commands/test.js';\nimport clearCommand from './commands/clear.js';\nimport createWorkflowCommand from './commands/workflow.js';\nimport monitorCommand from './commands/monitor.js';\nimport qualityCommand from './commands/quality.js';\nimport createRalphCommand from './commands/ralph.js';\nimport serviceCommand from './commands/service.js';\nimport { registerLoginCommand } from './commands/login.js';\nimport { registerSignupCommand } from './commands/signup.js';\nimport { registerLogoutCommand, registerDbCommands } from './commands/db.js';\nimport { createSweepCommand } from './commands/sweep.js';\nimport { createHooksCommand } from './commands/hooks.js';\nimport { createShellCommand } from './commands/shell.js';\nimport { createAPICommand } from './commands/api.js';\nimport { createCleanupProcessesCommand } from './commands/cleanup-processes.js';\nimport { createAutoBackgroundCommand } from './commands/auto-background.js';\nimport { createSettingsCommand } from './commands/settings.js';\nimport { createRetrievalCommands } from './commands/retrieval.js';\nimport { createDiscoveryCommands } from './commands/discovery.js';\nimport { createModelCommand } from './commands/model.js';\nimport { ProjectManager } from '../core/projects/project-manager.js';\nimport Database from 'better-sqlite3';\nimport { join } from 'path';\nimport { existsSync, mkdirSync } from 'fs';\nimport inquirer from 'inquirer';\nimport chalk from 'chalk';\nimport {\n loadStorageConfig,\n enableChromaDB,\n getStorageModeDescription,\n} from '../core/config/storage-config.js';\nimport { spawn } from 'child_process';\nimport { homedir } from 'os';\n\n// Read version from package.json\nimport { createRequire } from 'module';\nconst require = createRequire(import.meta.url);\nconst pkg = require('../../package.json');\nconst VERSION = pkg.version;\n\n// Check for updates on CLI startup\nUpdateChecker.checkForUpdates(VERSION, true).catch(() => {\n // Silently ignore errors\n});\n\n// Auto-start webhook and ngrok if notifications are enabled\nasync function startNotificationServices(): Promise<void> {\n // Skip in local-only mode\n if (isLocalOnly() || !isFeatureEnabled('whatsapp')) return;\n\n try {\n const { loadSMSConfig } = await import('../hooks/sms-notify.js');\n const config = loadSMSConfig();\n if (!config.enabled) return;\n\n const WEBHOOK_PORT = 3456;\n let webhookStarted = false;\n let ngrokStarted = false;\n\n // Check if webhook is already running\n const webhookRunning = await fetch(\n `http://localhost:${WEBHOOK_PORT}/health`\n )\n .then((r) => r.ok)\n .catch(() => false);\n\n if (!webhookRunning) {\n // Start webhook in background using the dist path\n const webhookPath = join(__dirname, '../hooks/sms-webhook.js');\n const webhookProcess = spawn('node', [webhookPath], {\n detached: true,\n stdio: 'ignore',\n env: { ...process.env, SMS_WEBHOOK_PORT: String(WEBHOOK_PORT) },\n });\n webhookProcess.unref();\n webhookStarted = true;\n }\n\n // Check if ngrok is running\n const ngrokRunning = await fetch('http://localhost:4040/api/tunnels')\n .then((r) => r.ok)\n .catch(() => false);\n\n if (!ngrokRunning) {\n // Start ngrok in background\n const ngrokProcess = spawn('ngrok', ['http', String(WEBHOOK_PORT)], {\n detached: true,\n stdio: 'ignore',\n });\n ngrokProcess.unref();\n ngrokStarted = true;\n }\n\n // Save ngrok URL after startup\n if (webhookStarted || ngrokStarted) {\n setTimeout(async () => {\n try {\n const tunnels = await fetch('http://localhost:4040/api/tunnels').then(\n (r) =>\n r.json() as Promise<{ tunnels: Array<{ public_url: string }> }>\n );\n const publicUrl = tunnels?.tunnels?.[0]?.public_url;\n if (publicUrl) {\n const configDir = join(homedir(), '.stackmemory');\n const configPath = join(configDir, 'ngrok-url.txt');\n const { writeFileSync, mkdirSync, existsSync } = await import('fs');\n if (!existsSync(configDir)) {\n mkdirSync(configDir, { recursive: true });\n }\n writeFileSync(configPath, publicUrl);\n console.log(\n chalk.gray(`[notify] Webhook: ${publicUrl}/sms/incoming`)\n );\n }\n } catch {\n // Ignore errors\n }\n }, 4000);\n }\n } catch {\n // Silently ignore - notifications are optional\n }\n}\n\nstartNotificationServices();\n\nprogram\n .name('stackmemory')\n .description(\n 'Lossless memory runtime for AI coding tools - organizes context as a call stack instead of linear chat logs, with team collaboration and infinite retention'\n )\n .version(VERSION);\n\nprogram\n .command('init')\n .description(\n `Initialize StackMemory in current project\n\nStorage Modes:\n SQLite (default): Local only, fast, no setup required\n ChromaDB (hybrid): Adds semantic search and cloud backup, requires API key`\n )\n .option('--sqlite', 'Use SQLite-only storage (default, skip prompts)')\n .option(\n '--chromadb',\n 'Enable ChromaDB for semantic search (prompts for API key)'\n )\n .option('--skip-storage-prompt', 'Skip storage configuration prompt')\n .action(async (options) => {\n try {\n const projectRoot = process.cwd();\n const dbDir = join(projectRoot, '.stackmemory');\n\n if (!existsSync(dbDir)) {\n mkdirSync(dbDir, { recursive: true });\n }\n\n // Handle storage configuration\n let storageConfig = loadStorageConfig();\n const isFirstTimeSetup =\n !storageConfig.chromadb.enabled && storageConfig.mode === 'sqlite';\n\n // Skip prompts if --sqlite flag or --skip-storage-prompt\n if (options.sqlite || options.skipStoragePrompt) {\n // Use SQLite-only (default)\n console.log(chalk.gray('Using SQLite-only storage mode.'));\n } else if (options.chromadb) {\n // User explicitly requested ChromaDB, prompt for API key\n await promptAndEnableChromaDB();\n } else if (isFirstTimeSetup && process.stdin.isTTY) {\n // Interactive mode - ask user about ChromaDB\n console.log(chalk.cyan('\\nStorage Configuration'));\n console.log(chalk.gray('StackMemory supports two storage modes:\\n'));\n console.log(chalk.white(' SQLite (default):'));\n console.log(chalk.gray(' - Local storage only'));\n console.log(chalk.gray(' - Fast and simple'));\n console.log(chalk.gray(' - No external dependencies\\n'));\n console.log(chalk.white(' ChromaDB (hybrid):'));\n console.log(chalk.gray(' - Semantic search across your context'));\n console.log(chalk.gray(' - Cloud backup capability'));\n console.log(chalk.gray(' - Requires ChromaDB API key\\n'));\n\n const { enableChroma } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'enableChroma',\n message: 'Enable ChromaDB for semantic search? (requires API key)',\n default: false,\n },\n ]);\n\n if (enableChroma) {\n await promptAndEnableChromaDB();\n } else {\n console.log(chalk.gray('Using SQLite-only storage mode.'));\n }\n }\n\n // Initialize SQLite database\n const dbPath = join(dbDir, 'context.db');\n const db = new Database(dbPath);\n new FrameManager(db, 'cli-project');\n\n logger.info('StackMemory initialized successfully', { projectRoot });\n console.log(\n chalk.green('\\n[OK] StackMemory initialized in'),\n projectRoot\n );\n\n // Show current storage mode\n storageConfig = loadStorageConfig();\n console.log(chalk.gray(`Storage mode: ${getStorageModeDescription()}`));\n\n db.close();\n } catch (error: unknown) {\n logger.error('Failed to initialize StackMemory', error as Error);\n console.error(\n chalk.red('[ERROR] Initialization failed:'),\n (error as Error).message\n );\n process.exit(1);\n }\n });\n\n/**\n * Prompt user for ChromaDB configuration and enable it\n */\nasync function promptAndEnableChromaDB(): Promise<void> {\n const answers = await inquirer.prompt([\n {\n type: 'password',\n name: 'apiKey',\n message: 'Enter your ChromaDB API key:',\n validate: (input: string) => {\n if (!input || input.trim().length === 0) {\n return 'API key is required for ChromaDB';\n }\n return true;\n },\n },\n {\n type: 'input',\n name: 'apiUrl',\n message: 'ChromaDB API URL (press Enter for default):',\n default: 'https://api.trychroma.com',\n },\n ]);\n\n enableChromaDB({\n apiKey: answers.apiKey,\n apiUrl: answers.apiUrl,\n });\n\n console.log(chalk.green('[OK] ChromaDB enabled for semantic search.'));\n console.log(\n chalk.gray('API key saved to ~/.stackmemory/storage-config.json')\n );\n}\n\nprogram\n .command('status')\n .description('Show current StackMemory status')\n .option('--all', 'Show all active frames across sessions')\n .option('--project', 'Show all active frames in current project')\n .option('--session <id>', 'Show frames for specific session')\n .action(async (options) => {\n return trace.command('stackmemory-status', options, async () => {\n try {\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n if (!existsSync(dbPath)) {\n console.log(\n '\u274C StackMemory not initialized. Run \"stackmemory init\" first.'\n );\n return;\n }\n\n // Check for updates and display if available\n await UpdateChecker.checkForUpdates(VERSION);\n\n // Initialize session manager and shared context\n await sessionManager.initialize();\n await sharedContextLayer.initialize();\n\n const session = await sessionManager.getOrCreateSession({\n projectPath: projectRoot,\n sessionId: options.session,\n });\n\n // Auto-discover shared context on startup\n const contextDiscovery = await sharedContextLayer.autoDiscoverContext();\n\n // Show context hints if available\n if (\n contextDiscovery.hasSharedContext &&\n contextDiscovery.sessionCount > 1\n ) {\n console.log(`\\n\uD83D\uDCA1 Shared Context Available:`);\n console.log(\n ` ${contextDiscovery.sessionCount} sessions with shared context`\n );\n\n if (contextDiscovery.recentPatterns.length > 0) {\n console.log(` Recent patterns:`);\n contextDiscovery.recentPatterns.slice(0, 3).forEach((p) => {\n console.log(\n ` \u2022 ${p.type}: ${p.pattern.slice(0, 50)} (${p.frequency}x)`\n );\n });\n }\n\n if (contextDiscovery.lastDecisions.length > 0) {\n console.log(\n ` Last decision: ${contextDiscovery.lastDecisions[0].decision.slice(0, 60)}`\n );\n }\n }\n\n const db = new Database(dbPath);\n const frameManager = new FrameManager(db, session.projectId);\n\n // Set query mode based on options\n if (options.all) {\n frameManager.setQueryMode(FrameQueryMode.ALL_ACTIVE);\n } else if (options.project) {\n frameManager.setQueryMode(FrameQueryMode.PROJECT_ACTIVE);\n }\n\n const activeFrames = frameManager.getActiveFramePath();\n const stackDepth = frameManager.getStackDepth();\n\n // Always get total counts across all sessions\n const totalStats = db\n .prepare(\n `\n SELECT \n COUNT(*) as total_frames,\n SUM(CASE WHEN state = 'active' THEN 1 ELSE 0 END) as active_frames,\n SUM(CASE WHEN state = 'closed' THEN 1 ELSE 0 END) as closed_frames,\n COUNT(DISTINCT run_id) as total_sessions\n FROM frames\n WHERE project_id = ?\n `\n )\n .get(session.projectId) as {\n total_frames: number;\n active_frames: number;\n closed_frames: number;\n total_sessions: number;\n };\n\n const contextCount = db\n .prepare(\n `\n SELECT COUNT(*) as count FROM contexts\n `\n )\n .get() as { count: number };\n\n const eventCount = db\n .prepare(\n `\n SELECT COUNT(*) as count FROM events e\n JOIN frames f ON e.frame_id = f.frame_id\n WHERE f.project_id = ?\n `\n )\n .get(session.projectId) as { count: number };\n\n console.log('\uD83D\uDCCA StackMemory Status:');\n console.log(\n ` Session: ${session.sessionId.slice(0, 8)} (${session.state}, ${Math.round((Date.now() - session.startedAt) / 1000 / 60)}min old)`\n );\n console.log(` Project: ${session.projectId}`);\n if (session.branch) {\n console.log(` Branch: ${session.branch}`);\n }\n\n // Show total database statistics\n console.log(`\\n Database Statistics (this project):`);\n console.log(\n ` Frames: ${totalStats.total_frames || 0} (${totalStats.active_frames || 0} active, ${totalStats.closed_frames || 0} closed)`\n );\n console.log(` Events: ${eventCount.count || 0}`);\n console.log(` Sessions: ${totalStats.total_sessions || 0}`);\n console.log(\n ` Cached contexts: ${contextCount.count || 0} (global)`\n );\n\n // Show recent activity\n const recentFrames = db\n .prepare(\n `\n SELECT name, type, state, datetime(created_at, 'unixepoch') as created\n FROM frames\n WHERE project_id = ?\n ORDER BY created_at DESC\n LIMIT 3\n `\n )\n .all(session.projectId) as Array<{\n name: string;\n type: string;\n state: string;\n created: string;\n }>;\n\n if (recentFrames.length > 0) {\n console.log(`\\n Recent Activity:`);\n recentFrames.forEach((f) => {\n const stateIcon = f.state === 'active' ? '\uD83D\uDFE2' : '\u26AB';\n console.log(\n ` ${stateIcon} ${f.name} [${f.type}] - ${f.created}`\n );\n });\n }\n\n console.log(`\\n Current Session:`);\n console.log(` Stack depth: ${stackDepth}`);\n console.log(` Active frames: ${activeFrames.length}`);\n\n if (activeFrames.length > 0) {\n activeFrames.forEach((frame, i) => {\n const indent = ' ' + ' '.repeat(frame.depth || i);\n const prefix = i === 0 ? '\u2514\u2500' : ' \u2514\u2500';\n console.log(`${indent}${prefix} ${frame.name} [${frame.type}]`);\n });\n }\n\n // Show other sessions if in default mode\n if (!options.all && !options.project) {\n const otherSessions = await sessionManager.listSessions({\n projectId: session.projectId,\n state: 'active',\n });\n\n const otherActive = otherSessions.filter(\n (s) => s.sessionId !== session.sessionId\n );\n if (otherActive.length > 0) {\n console.log(`\\n Other Active Sessions (same project):`);\n otherActive.forEach((s) => {\n const age = Math.round(\n (Date.now() - s.lastActiveAt) / 1000 / 60 / 60\n );\n console.log(\n ` - ${s.sessionId.slice(0, 8)}: ${s.branch || 'main'}, ${age}h old`\n );\n });\n console.log(`\\n Tip: Use --all to see frames across sessions`);\n }\n }\n\n db.close();\n } catch (error: unknown) {\n logger.error('Failed to get status', error as Error);\n console.error('\u274C Status check failed:', (error as Error).message);\n process.exit(1);\n }\n });\n });\n\nprogram\n .command('update-check')\n .description('Check for StackMemory updates')\n .action(async () => {\n try {\n console.log('\uD83D\uDD0D Checking for updates...');\n await UpdateChecker.forceCheck(VERSION);\n } catch (error: unknown) {\n logger.error('Update check failed', error as Error);\n console.error('\u274C Update check failed:', (error as Error).message);\n process.exit(1);\n }\n });\n\nprogram\n .command('progress')\n .description('Show current progress and recent changes')\n .action(async () => {\n try {\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n if (!existsSync(dbPath)) {\n console.log(\n '\u274C StackMemory not initialized. Run \"stackmemory init\" first.'\n );\n return;\n }\n\n const progress = new ProgressTracker(projectRoot);\n console.log(progress.getSummary());\n } catch (error: unknown) {\n logger.error('Failed to show progress', error as Error);\n console.error('\u274C Failed to show progress:', (error as Error).message);\n process.exit(1);\n }\n });\n\nprogram\n .command('mcp-server')\n .description('Start StackMemory MCP server for Claude Desktop')\n .option('-p, --project <path>', 'Project root directory', process.cwd())\n .action(async (options) => {\n try {\n const { runMCPServer } = await import('../integrations/mcp/server.js');\n\n // Set project root\n process.env['PROJECT_ROOT'] = options.project;\n\n console.log('\uD83D\uDE80 Starting StackMemory MCP Server...');\n console.log(` Project: ${options.project}`);\n console.log(` Version: ${VERSION}`);\n\n // Check for updates silently\n UpdateChecker.checkForUpdates(VERSION, true).catch(() => {});\n\n // Start the MCP server\n await runMCPServer();\n } catch (error: unknown) {\n logger.error('Failed to start MCP server', error as Error);\n console.error('\u274C MCP server failed:', (error as Error).message);\n process.exit(1);\n }\n });\n\n// Add test context command\nprogram\n .command('context:test')\n .description('Test context persistence by creating sample frames')\n .action(async () => {\n try {\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n if (!existsSync(dbPath)) {\n console.log(\n '\u274C StackMemory not initialized. Run \"stackmemory init\" first.'\n );\n return;\n }\n\n const db = new Database(dbPath);\n const frameManager = new FrameManager(db, 'cli-project');\n\n // Create test frames\n console.log('\uD83D\uDCDD Creating test context frames...');\n\n const rootFrame = frameManager.createFrame({\n type: 'task',\n name: 'Test Session',\n inputs: { test: true, timestamp: new Date().toISOString() },\n });\n\n const taskFrame = frameManager.createFrame({\n type: 'subtask',\n name: 'Sample Task',\n inputs: { description: 'Testing context persistence' },\n parentFrameId: rootFrame,\n });\n\n const commandFrame = frameManager.createFrame({\n type: 'tool_scope',\n name: 'test-command',\n inputs: { args: ['--test'] },\n parentFrameId: taskFrame,\n });\n\n // Add some events\n frameManager.addEvent(\n 'observation',\n {\n message: 'Test event recorded',\n },\n commandFrame\n );\n\n console.log('\u2705 Test frames created!');\n console.log(`\uD83D\uDCCA Stack depth: ${frameManager.getStackDepth()}`);\n console.log(\n `\uD83D\uDD04 Active frames: ${frameManager.getActiveFramePath().length}`\n );\n\n // Close one frame to test state changes\n frameManager.closeFrame(commandFrame);\n console.log(\n `\uD83D\uDCCA After closing command frame: depth = ${frameManager.getStackDepth()}`\n );\n\n db.close();\n } catch (error: unknown) {\n logger.error('Test context failed', error as Error);\n console.error('\u274C Test failed:', (error as Error).message);\n process.exit(1);\n }\n });\n\n// Register project management commands\n// Register command modules\nregisterOnboardingCommand(program);\nregisterSignupCommand(program);\nregisterLoginCommand(program);\nregisterLogoutCommand(program);\nregisterDbCommands(program);\nregisterProjectCommands(program);\nregisterWorktreeCommands(program);\n\n// Register Linear integration commands (lazy-loaded, optional)\nif (isFeatureEnabled('linear')) {\n import('./commands/linear.js')\n .then(({ registerLinearCommands }) => registerLinearCommands(program))\n .catch(() => {\n // Linear integration not available - silently skip\n });\n}\n\n// Register session management commands\nprogram.addCommand(createSessionCommands());\n\n// Register enhanced CLI commands\nprogram.addCommand(createTaskCommands());\nprogram.addCommand(createSearchCommand());\nprogram.addCommand(createLogCommand());\nprogram.addCommand(createContextCommands());\nprogram.addCommand(createConfigCommand());\nprogram.addCommand(createHandoffCommand());\nprogram.addCommand(createDecisionCommand());\nprogram.addCommand(createMemoryCommand());\nprogram.addCommand(createSkillsCommand());\nprogram.addCommand(createTestCommand());\nprogram.addCommand(clearCommand);\nprogram.addCommand(createWorkflowCommand());\nprogram.addCommand(monitorCommand);\nprogram.addCommand(qualityCommand);\nprogram.addCommand(createRalphCommand());\nprogram.addCommand(serviceCommand);\nprogram.addCommand(createSweepCommand());\nprogram.addCommand(createHooksCommand());\nprogram.addCommand(createShellCommand());\nprogram.addCommand(createAPICommand());\nprogram.addCommand(createCleanupProcessesCommand());\nprogram.addCommand(createAutoBackgroundCommand());\nprogram.addCommand(createSettingsCommand());\n\n// Register WhatsApp/SMS commands (lazy-loaded, optional)\nif (isFeatureEnabled('whatsapp')) {\n import('./commands/sms-notify.js')\n .then(({ createSMSNotifyCommand }) =>\n program.addCommand(createSMSNotifyCommand())\n )\n .catch(() => {\n // WhatsApp integration not available - silently skip\n });\n}\nprogram.addCommand(createRetrievalCommands());\nprogram.addCommand(createDiscoveryCommands());\nprogram.addCommand(createModelCommand());\n\n// Register dashboard command\nprogram\n .command('dashboard')\n .description('Display monitoring dashboard in terminal')\n .option('-w, --watch', 'Auto-refresh dashboard')\n .option('-i, --interval <seconds>', 'Refresh interval in seconds', '5')\n .action(async (options) => {\n const { dashboardCommand } = await import('./commands/dashboard.js');\n await dashboardCommand.handler(options);\n });\n\n// Auto-detect current project on startup\nif (process.argv.length > 2) {\n const manager = ProjectManager.getInstance();\n manager.detectProject().catch(() => {\n // Silently fail if not in a project directory\n });\n}\n\n// Only parse when running as main module (not when imported for testing)\nconst isMainModule =\n import.meta.url === `file://${process.argv[1]}` ||\n process.argv[1]?.endsWith('/stackmemory') ||\n process.argv[1]?.endsWith('index.ts') ||\n process.argv[1]?.includes('tsx');\n\nif (isMainModule) {\n program.parse();\n}\n\nexport { program };\n"],
|
|
5
|
-
"mappings": ";;;;;AAOA,QAAQ,IAAI,iBAAiB,IAAI;AAGjC,OAAO;AAGP,SAAS,mBAAmB,aAAa;AACzC,kBAAkB;AAElB,SAAS,eAAe;AACxB,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB,sBAAsB;AAC/C,SAAS,0BAA0B;AACnC,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAChC,SAAS,+BAA+B;AACxC,SAAS,6BAA6B;AACtC,SAAS,kBAAkB,mBAAmB;AAC9C,SAAS,gCAAgC;AACzC,SAAS,iCAAiC;AAC1C,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AACpC,SAAS,wBAAwB;AACjC,S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cAAc;AAChB,UAAQ,MAAM;AAChB;",
|
|
4
|
+
"sourcesContent": ["#!/usr/bin/env node\n/**\n * StackMemory CLI\n * Command-line interface for StackMemory operations\n */\n\n// Set environment flag for CLI usage to skip async context bridge\nprocess.env['STACKMEMORY_CLI'] = 'true';\n\n// Load environment variables\nimport 'dotenv/config';\n\n// Initialize tracing system early\nimport { initializeTracing, trace } from '../core/trace/index.js';\ninitializeTracing();\n\nimport { program } from 'commander';\nimport { logger } from '../core/monitoring/logger.js';\nimport { FrameManager } from '../core/context/index.js';\nimport { sessionManager, FrameQueryMode } from '../core/session/index.js';\nimport { sharedContextLayer } from '../core/context/shared-context-layer.js';\nimport { UpdateChecker } from '../core/utils/update-checker.js';\nimport { ProgressTracker } from '../core/monitoring/progress-tracker.js';\nimport { registerProjectCommands } from './commands/projects.js';\nimport { createSessionCommands } from './commands/session.js';\nimport { isFeatureEnabled, isLocalOnly } from '../core/config/feature-flags.js';\nimport { registerWorktreeCommands } from './commands/worktree.js';\nimport { registerOnboardingCommand } from './commands/onboard.js';\nimport { createTaskCommands } from './commands/tasks.js';\nimport { createSearchCommand } from './commands/search.js';\nimport { createLogCommand } from './commands/log.js';\nimport { createContextCommands } from './commands/context.js';\nimport { createConfigCommand } from './commands/config.js';\nimport { createHandoffCommand } from './commands/handoff.js';\nimport {\n createDecisionCommand,\n createMemoryCommand,\n} from './commands/decision.js';\nimport { createSkillsCommand } from './commands/skills.js';\nimport { createTestCommand } from './commands/test.js';\nimport clearCommand from './commands/clear.js';\nimport createWorkflowCommand from './commands/workflow.js';\nimport monitorCommand from './commands/monitor.js';\nimport qualityCommand from './commands/quality.js';\nimport createRalphCommand from './commands/ralph.js';\nimport serviceCommand from './commands/service.js';\nimport { registerLoginCommand } from './commands/login.js';\nimport { registerSignupCommand } from './commands/signup.js';\nimport { registerLogoutCommand, registerDbCommands } from './commands/db.js';\nimport { createSweepCommand } from './commands/sweep.js';\nimport { createHooksCommand } from './commands/hooks.js';\nimport { createShellCommand } from './commands/shell.js';\nimport { createAPICommand } from './commands/api.js';\nimport { createCleanupProcessesCommand } from './commands/cleanup-processes.js';\nimport { createAutoBackgroundCommand } from './commands/auto-background.js';\nimport { createSettingsCommand } from './commands/settings.js';\nimport { createRetrievalCommands } from './commands/retrieval.js';\nimport { createDiscoveryCommands } from './commands/discovery.js';\nimport { createModelCommand } from './commands/model.js';\nimport { registerSetupCommands } from './commands/setup.js';\nimport { ProjectManager } from '../core/projects/project-manager.js';\nimport Database from 'better-sqlite3';\nimport { join } from 'path';\nimport { existsSync, mkdirSync } from 'fs';\nimport inquirer from 'inquirer';\nimport chalk from 'chalk';\nimport { enableChromaDB } from '../core/config/storage-config.js';\nimport { spawn } from 'child_process';\nimport { homedir } from 'os';\n\n// Read version from package.json\nimport { createRequire } from 'module';\nconst require = createRequire(import.meta.url);\nconst pkg = require('../../package.json');\nconst VERSION = pkg.version;\n\n// Check for updates on CLI startup\nUpdateChecker.checkForUpdates(VERSION, true).catch(() => {\n // Silently ignore errors\n});\n\n// Auto-start webhook and ngrok if notifications are enabled\nasync function startNotificationServices(): Promise<void> {\n // Skip in local-only mode\n if (isLocalOnly() || !isFeatureEnabled('whatsapp')) return;\n\n try {\n const { loadSMSConfig } = await import('../hooks/sms-notify.js');\n const config = loadSMSConfig();\n if (!config.enabled) return;\n\n const WEBHOOK_PORT = 3456;\n let webhookStarted = false;\n let ngrokStarted = false;\n\n // Check if webhook is already running\n const webhookRunning = await fetch(\n `http://localhost:${WEBHOOK_PORT}/health`\n )\n .then((r) => r.ok)\n .catch(() => false);\n\n if (!webhookRunning) {\n // Start webhook in background using the dist path\n const webhookPath = join(__dirname, '../hooks/sms-webhook.js');\n const webhookProcess = spawn('node', [webhookPath], {\n detached: true,\n stdio: 'ignore',\n env: { ...process.env, SMS_WEBHOOK_PORT: String(WEBHOOK_PORT) },\n });\n webhookProcess.unref();\n webhookStarted = true;\n }\n\n // Check if ngrok is running\n const ngrokRunning = await fetch('http://localhost:4040/api/tunnels')\n .then((r) => r.ok)\n .catch(() => false);\n\n if (!ngrokRunning) {\n // Start ngrok in background\n const ngrokProcess = spawn('ngrok', ['http', String(WEBHOOK_PORT)], {\n detached: true,\n stdio: 'ignore',\n });\n ngrokProcess.unref();\n ngrokStarted = true;\n }\n\n // Save ngrok URL after startup\n if (webhookStarted || ngrokStarted) {\n setTimeout(async () => {\n try {\n const tunnels = await fetch('http://localhost:4040/api/tunnels').then(\n (r) =>\n r.json() as Promise<{ tunnels: Array<{ public_url: string }> }>\n );\n const publicUrl = tunnels?.tunnels?.[0]?.public_url;\n if (publicUrl) {\n const configDir = join(homedir(), '.stackmemory');\n const configPath = join(configDir, 'ngrok-url.txt');\n const { writeFileSync, mkdirSync, existsSync } = await import('fs');\n if (!existsSync(configDir)) {\n mkdirSync(configDir, { recursive: true });\n }\n writeFileSync(configPath, publicUrl);\n console.log(\n chalk.gray(`[notify] Webhook: ${publicUrl}/sms/incoming`)\n );\n }\n } catch {\n // Ignore errors\n }\n }, 4000);\n }\n } catch {\n // Silently ignore - notifications are optional\n }\n}\n\nstartNotificationServices();\n\nprogram\n .name('stackmemory')\n .description(\n 'Lossless memory runtime for AI coding tools - organizes context as a call stack instead of linear chat logs, with team collaboration and infinite retention'\n )\n .version(VERSION);\n\nprogram\n .command('init')\n .description(\n `Initialize StackMemory in current project (zero-config by default)\n\nOptions:\n --interactive Ask configuration questions\n --chromadb Enable ChromaDB semantic search (prompts for API key)`\n )\n .option('-i, --interactive', 'Interactive mode with configuration prompts')\n .option(\n '--chromadb',\n 'Enable ChromaDB for semantic search (prompts for API key)'\n )\n .action(async (options) => {\n try {\n const projectRoot = process.cwd();\n const dbDir = join(projectRoot, '.stackmemory');\n\n // Check if already initialized\n const alreadyInit = existsSync(join(dbDir, 'context.db'));\n if (alreadyInit && !options.interactive) {\n console.log(chalk.yellow('StackMemory already initialized.'));\n console.log(chalk.gray('Run with --interactive to reconfigure.'));\n return;\n }\n\n if (!existsSync(dbDir)) {\n mkdirSync(dbDir, { recursive: true });\n }\n\n // Zero-config by default - just use SQLite, no questions\n if (options.chromadb) {\n await promptAndEnableChromaDB();\n } else if (options.interactive && process.stdin.isTTY) {\n // Only ask questions in interactive mode\n console.log(chalk.cyan('\\nStorage Configuration'));\n console.log(\n chalk.gray('SQLite (default) is fast and requires no setup.')\n );\n console.log(\n chalk.gray('ChromaDB adds semantic search but requires an API key.\\n')\n );\n\n const { enableChroma } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'enableChroma',\n message: 'Enable ChromaDB for semantic search?',\n default: false,\n },\n ]);\n\n if (enableChroma) {\n await promptAndEnableChromaDB();\n }\n }\n\n // Initialize SQLite database\n const dbPath = join(dbDir, 'context.db');\n const db = new Database(dbPath);\n new FrameManager(db, 'cli-project');\n\n logger.info('StackMemory initialized successfully', { projectRoot });\n console.log(chalk.green('\\n[OK] StackMemory initialized'));\n console.log(chalk.gray(` Project: ${projectRoot}`));\n console.log(chalk.gray(` Storage: SQLite (local)`));\n\n // Show next steps\n console.log(chalk.cyan('\\nNext steps:'));\n console.log(\n chalk.white(' 1. stackmemory setup-mcp') +\n chalk.gray(' # Configure Claude Code integration')\n );\n console.log(\n chalk.white(' 2. stackmemory status') +\n chalk.gray(' # Check status')\n );\n console.log(\n chalk.white(' 3. stackmemory doctor') +\n chalk.gray(' # Diagnose issues')\n );\n\n db.close();\n } catch (error: unknown) {\n logger.error('Failed to initialize StackMemory', error as Error);\n console.error(chalk.red('\\n[ERROR] Initialization failed'));\n console.error(chalk.gray(` Reason: ${(error as Error).message}`));\n console.error(\n chalk.gray(\n ' Fix: Ensure you have write permissions to the current directory'\n )\n );\n console.error(chalk.gray(' Run: stackmemory doctor'));\n process.exit(1);\n }\n });\n\n/**\n * Prompt user for ChromaDB configuration and enable it\n */\nasync function promptAndEnableChromaDB(): Promise<void> {\n const answers = await inquirer.prompt([\n {\n type: 'password',\n name: 'apiKey',\n message: 'Enter your ChromaDB API key:',\n validate: (input: string) => {\n if (!input || input.trim().length === 0) {\n return 'API key is required for ChromaDB';\n }\n return true;\n },\n },\n {\n type: 'input',\n name: 'apiUrl',\n message: 'ChromaDB API URL (press Enter for default):',\n default: 'https://api.trychroma.com',\n },\n ]);\n\n enableChromaDB({\n apiKey: answers.apiKey,\n apiUrl: answers.apiUrl,\n });\n\n console.log(chalk.green('[OK] ChromaDB enabled for semantic search.'));\n console.log(\n chalk.gray('API key saved to ~/.stackmemory/storage-config.json')\n );\n}\n\nprogram\n .command('status')\n .description('Show current StackMemory status')\n .option('--all', 'Show all active frames across sessions')\n .option('--project', 'Show all active frames in current project')\n .option('--session <id>', 'Show frames for specific session')\n .action(async (options) => {\n return trace.command('stackmemory-status', options, async () => {\n try {\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n if (!existsSync(dbPath)) {\n console.log(\n '\u274C StackMemory not initialized. Run \"stackmemory init\" first.'\n );\n return;\n }\n\n // Check for updates and display if available\n await UpdateChecker.checkForUpdates(VERSION);\n\n // Initialize session manager and shared context\n await sessionManager.initialize();\n await sharedContextLayer.initialize();\n\n const session = await sessionManager.getOrCreateSession({\n projectPath: projectRoot,\n sessionId: options.session,\n });\n\n // Auto-discover shared context on startup\n const contextDiscovery = await sharedContextLayer.autoDiscoverContext();\n\n // Show context hints if available\n if (\n contextDiscovery.hasSharedContext &&\n contextDiscovery.sessionCount > 1\n ) {\n console.log(`\\n\uD83D\uDCA1 Shared Context Available:`);\n console.log(\n ` ${contextDiscovery.sessionCount} sessions with shared context`\n );\n\n if (contextDiscovery.recentPatterns.length > 0) {\n console.log(` Recent patterns:`);\n contextDiscovery.recentPatterns.slice(0, 3).forEach((p) => {\n console.log(\n ` \u2022 ${p.type}: ${p.pattern.slice(0, 50)} (${p.frequency}x)`\n );\n });\n }\n\n if (contextDiscovery.lastDecisions.length > 0) {\n console.log(\n ` Last decision: ${contextDiscovery.lastDecisions[0].decision.slice(0, 60)}`\n );\n }\n }\n\n const db = new Database(dbPath);\n const frameManager = new FrameManager(db, session.projectId);\n\n // Set query mode based on options\n if (options.all) {\n frameManager.setQueryMode(FrameQueryMode.ALL_ACTIVE);\n } else if (options.project) {\n frameManager.setQueryMode(FrameQueryMode.PROJECT_ACTIVE);\n }\n\n const activeFrames = frameManager.getActiveFramePath();\n const stackDepth = frameManager.getStackDepth();\n\n // Always get total counts across all sessions\n const totalStats = db\n .prepare(\n `\n SELECT \n COUNT(*) as total_frames,\n SUM(CASE WHEN state = 'active' THEN 1 ELSE 0 END) as active_frames,\n SUM(CASE WHEN state = 'closed' THEN 1 ELSE 0 END) as closed_frames,\n COUNT(DISTINCT run_id) as total_sessions\n FROM frames\n WHERE project_id = ?\n `\n )\n .get(session.projectId) as {\n total_frames: number;\n active_frames: number;\n closed_frames: number;\n total_sessions: number;\n };\n\n const contextCount = db\n .prepare(\n `\n SELECT COUNT(*) as count FROM contexts\n `\n )\n .get() as { count: number };\n\n const eventCount = db\n .prepare(\n `\n SELECT COUNT(*) as count FROM events e\n JOIN frames f ON e.frame_id = f.frame_id\n WHERE f.project_id = ?\n `\n )\n .get(session.projectId) as { count: number };\n\n console.log('\uD83D\uDCCA StackMemory Status:');\n console.log(\n ` Session: ${session.sessionId.slice(0, 8)} (${session.state}, ${Math.round((Date.now() - session.startedAt) / 1000 / 60)}min old)`\n );\n console.log(` Project: ${session.projectId}`);\n if (session.branch) {\n console.log(` Branch: ${session.branch}`);\n }\n\n // Show total database statistics\n console.log(`\\n Database Statistics (this project):`);\n console.log(\n ` Frames: ${totalStats.total_frames || 0} (${totalStats.active_frames || 0} active, ${totalStats.closed_frames || 0} closed)`\n );\n console.log(` Events: ${eventCount.count || 0}`);\n console.log(` Sessions: ${totalStats.total_sessions || 0}`);\n console.log(\n ` Cached contexts: ${contextCount.count || 0} (global)`\n );\n\n // Show recent activity\n const recentFrames = db\n .prepare(\n `\n SELECT name, type, state, datetime(created_at, 'unixepoch') as created\n FROM frames\n WHERE project_id = ?\n ORDER BY created_at DESC\n LIMIT 3\n `\n )\n .all(session.projectId) as Array<{\n name: string;\n type: string;\n state: string;\n created: string;\n }>;\n\n if (recentFrames.length > 0) {\n console.log(`\\n Recent Activity:`);\n recentFrames.forEach((f) => {\n const stateIcon = f.state === 'active' ? '\uD83D\uDFE2' : '\u26AB';\n console.log(\n ` ${stateIcon} ${f.name} [${f.type}] - ${f.created}`\n );\n });\n }\n\n console.log(`\\n Current Session:`);\n console.log(` Stack depth: ${stackDepth}`);\n console.log(` Active frames: ${activeFrames.length}`);\n\n if (activeFrames.length > 0) {\n activeFrames.forEach((frame, i) => {\n const indent = ' ' + ' '.repeat(frame.depth || i);\n const prefix = i === 0 ? '\u2514\u2500' : ' \u2514\u2500';\n console.log(`${indent}${prefix} ${frame.name} [${frame.type}]`);\n });\n }\n\n // Show other sessions if in default mode\n if (!options.all && !options.project) {\n const otherSessions = await sessionManager.listSessions({\n projectId: session.projectId,\n state: 'active',\n });\n\n const otherActive = otherSessions.filter(\n (s) => s.sessionId !== session.sessionId\n );\n if (otherActive.length > 0) {\n console.log(`\\n Other Active Sessions (same project):`);\n otherActive.forEach((s) => {\n const age = Math.round(\n (Date.now() - s.lastActiveAt) / 1000 / 60 / 60\n );\n console.log(\n ` - ${s.sessionId.slice(0, 8)}: ${s.branch || 'main'}, ${age}h old`\n );\n });\n console.log(`\\n Tip: Use --all to see frames across sessions`);\n }\n }\n\n db.close();\n } catch (error: unknown) {\n logger.error('Failed to get status', error as Error);\n console.error('\u274C Status check failed:', (error as Error).message);\n process.exit(1);\n }\n });\n });\n\nprogram\n .command('update-check')\n .description('Check for StackMemory updates')\n .action(async () => {\n try {\n console.log('\uD83D\uDD0D Checking for updates...');\n await UpdateChecker.forceCheck(VERSION);\n } catch (error: unknown) {\n logger.error('Update check failed', error as Error);\n console.error('\u274C Update check failed:', (error as Error).message);\n process.exit(1);\n }\n });\n\nprogram\n .command('progress')\n .description('Show current progress and recent changes')\n .action(async () => {\n try {\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n if (!existsSync(dbPath)) {\n console.log(\n '\u274C StackMemory not initialized. Run \"stackmemory init\" first.'\n );\n return;\n }\n\n const progress = new ProgressTracker(projectRoot);\n console.log(progress.getSummary());\n } catch (error: unknown) {\n logger.error('Failed to show progress', error as Error);\n console.error('\u274C Failed to show progress:', (error as Error).message);\n process.exit(1);\n }\n });\n\nprogram\n .command('mcp-server')\n .description('Start StackMemory MCP server for Claude Desktop')\n .option('-p, --project <path>', 'Project root directory', process.cwd())\n .action(async (options) => {\n try {\n const { runMCPServer } = await import('../integrations/mcp/server.js');\n\n // Set project root\n process.env['PROJECT_ROOT'] = options.project;\n\n console.log('\uD83D\uDE80 Starting StackMemory MCP Server...');\n console.log(` Project: ${options.project}`);\n console.log(` Version: ${VERSION}`);\n\n // Check for updates silently\n UpdateChecker.checkForUpdates(VERSION, true).catch(() => {});\n\n // Start the MCP server\n await runMCPServer();\n } catch (error: unknown) {\n logger.error('Failed to start MCP server', error as Error);\n console.error('\u274C MCP server failed:', (error as Error).message);\n process.exit(1);\n }\n });\n\n// Add test context command\nprogram\n .command('context:test')\n .description('Test context persistence by creating sample frames')\n .action(async () => {\n try {\n const projectRoot = process.cwd();\n const dbPath = join(projectRoot, '.stackmemory', 'context.db');\n\n if (!existsSync(dbPath)) {\n console.log(\n '\u274C StackMemory not initialized. Run \"stackmemory init\" first.'\n );\n return;\n }\n\n const db = new Database(dbPath);\n const frameManager = new FrameManager(db, 'cli-project');\n\n // Create test frames\n console.log('\uD83D\uDCDD Creating test context frames...');\n\n const rootFrame = frameManager.createFrame({\n type: 'task',\n name: 'Test Session',\n inputs: { test: true, timestamp: new Date().toISOString() },\n });\n\n const taskFrame = frameManager.createFrame({\n type: 'subtask',\n name: 'Sample Task',\n inputs: { description: 'Testing context persistence' },\n parentFrameId: rootFrame,\n });\n\n const commandFrame = frameManager.createFrame({\n type: 'tool_scope',\n name: 'test-command',\n inputs: { args: ['--test'] },\n parentFrameId: taskFrame,\n });\n\n // Add some events\n frameManager.addEvent(\n 'observation',\n {\n message: 'Test event recorded',\n },\n commandFrame\n );\n\n console.log('\u2705 Test frames created!');\n console.log(`\uD83D\uDCCA Stack depth: ${frameManager.getStackDepth()}`);\n console.log(\n `\uD83D\uDD04 Active frames: ${frameManager.getActiveFramePath().length}`\n );\n\n // Close one frame to test state changes\n frameManager.closeFrame(commandFrame);\n console.log(\n `\uD83D\uDCCA After closing command frame: depth = ${frameManager.getStackDepth()}`\n );\n\n db.close();\n } catch (error: unknown) {\n logger.error('Test context failed', error as Error);\n console.error('\u274C Test failed:', (error as Error).message);\n process.exit(1);\n }\n });\n\n// Register project management commands\n// Register command modules\nregisterOnboardingCommand(program);\nregisterSignupCommand(program);\nregisterLoginCommand(program);\nregisterLogoutCommand(program);\nregisterDbCommands(program);\nregisterProjectCommands(program);\nregisterWorktreeCommands(program);\n\n// Register Linear integration commands (lazy-loaded, optional)\nif (isFeatureEnabled('linear')) {\n import('./commands/linear.js')\n .then(({ registerLinearCommands }) => registerLinearCommands(program))\n .catch(() => {\n // Linear integration not available - silently skip\n });\n}\n\n// Register session management commands\nprogram.addCommand(createSessionCommands());\n\n// Register enhanced CLI commands\nprogram.addCommand(createTaskCommands());\nprogram.addCommand(createSearchCommand());\nprogram.addCommand(createLogCommand());\nprogram.addCommand(createContextCommands());\nprogram.addCommand(createConfigCommand());\nprogram.addCommand(createHandoffCommand());\nprogram.addCommand(createDecisionCommand());\nprogram.addCommand(createMemoryCommand());\nprogram.addCommand(createSkillsCommand());\nprogram.addCommand(createTestCommand());\nprogram.addCommand(clearCommand);\nprogram.addCommand(createWorkflowCommand());\nprogram.addCommand(monitorCommand);\nprogram.addCommand(qualityCommand);\nprogram.addCommand(createRalphCommand());\nprogram.addCommand(serviceCommand);\nprogram.addCommand(createSweepCommand());\nprogram.addCommand(createHooksCommand());\nprogram.addCommand(createShellCommand());\nprogram.addCommand(createAPICommand());\nprogram.addCommand(createCleanupProcessesCommand());\nprogram.addCommand(createAutoBackgroundCommand());\nprogram.addCommand(createSettingsCommand());\n\n// Register WhatsApp/SMS commands (lazy-loaded, optional)\nif (isFeatureEnabled('whatsapp')) {\n import('./commands/sms-notify.js')\n .then(({ createSMSNotifyCommand }) =>\n program.addCommand(createSMSNotifyCommand())\n )\n .catch(() => {\n // WhatsApp integration not available - silently skip\n });\n}\nprogram.addCommand(createRetrievalCommands());\nprogram.addCommand(createDiscoveryCommands());\nprogram.addCommand(createModelCommand());\n\n// Register setup and diagnostic commands\nregisterSetupCommands(program);\n\n// Register dashboard command\nprogram\n .command('dashboard')\n .description('Display monitoring dashboard in terminal')\n .option('-w, --watch', 'Auto-refresh dashboard')\n .option('-i, --interval <seconds>', 'Refresh interval in seconds', '5')\n .action(async (options) => {\n const { dashboardCommand } = await import('./commands/dashboard.js');\n await dashboardCommand.handler(options);\n });\n\n// Auto-detect current project on startup\nif (process.argv.length > 2) {\n const manager = ProjectManager.getInstance();\n manager.detectProject().catch(() => {\n // Silently fail if not in a project directory\n });\n}\n\n// Only parse when running as main module (not when imported for testing)\nconst isMainModule =\n import.meta.url === `file://${process.argv[1]}` ||\n process.argv[1]?.endsWith('/stackmemory') ||\n process.argv[1]?.endsWith('index.ts') ||\n process.argv[1]?.includes('tsx');\n\nif (isMainModule) {\n program.parse();\n}\n\nexport { program };\n"],
|
|
5
|
+
"mappings": ";;;;;AAOA,QAAQ,IAAI,iBAAiB,IAAI;AAGjC,OAAO;AAGP,SAAS,mBAAmB,aAAa;AACzC,kBAAkB;AAElB,SAAS,eAAe;AACxB,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB,sBAAsB;AAC/C,SAAS,0BAA0B;AACnC,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAChC,SAAS,+BAA+B;AACxC,SAAS,6BAA6B;AACtC,SAAS,kBAAkB,mBAAmB;AAC9C,SAAS,gCAAgC;AACzC,SAAS,iCAAiC;AAC1C,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AACpC,SAAS,w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C,GAAG,SAAS,UAAU,KACpC,QAAQ,KAAK,CAAC,GAAG,SAAS,KAAK;AAEjC,IAAI,cAAc;AAChB,UAAQ,MAAM;AAChB;",
|
|
6
6
|
"names": ["require", "mkdirSync", "existsSync"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stackmemoryai/stackmemory",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.40",
|
|
4
4
|
"description": "Lossless memory runtime for AI coding tools - organizes context as a call stack instead of linear chat logs, with team collaboration and infinite retention",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=20.0.0",
|
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
/**
|
|
4
4
|
* Auto-install Claude hooks during npm install
|
|
5
5
|
* This runs as a postinstall script to set up tracing hooks and daemon
|
|
6
|
+
*
|
|
7
|
+
* INTERACTIVE: Asks for user consent before modifying ~/.claude
|
|
6
8
|
*/
|
|
7
9
|
|
|
8
10
|
import {
|
|
@@ -14,6 +16,7 @@ import {
|
|
|
14
16
|
} from 'fs';
|
|
15
17
|
import { join } from 'path';
|
|
16
18
|
import { homedir } from 'os';
|
|
19
|
+
import { createInterface } from 'readline';
|
|
17
20
|
|
|
18
21
|
import { fileURLToPath } from 'url';
|
|
19
22
|
import { dirname } from 'path';
|
|
@@ -27,12 +30,63 @@ const templatesDir = join(__dirname, '..', 'templates', 'claude-hooks');
|
|
|
27
30
|
const stackmemoryBinDir = join(homedir(), '.stackmemory', 'bin');
|
|
28
31
|
const distDir = join(__dirname, '..', 'dist');
|
|
29
32
|
|
|
33
|
+
/**
|
|
34
|
+
* Ask user for confirmation before installing hooks
|
|
35
|
+
* Returns true if user consents, false otherwise
|
|
36
|
+
*/
|
|
37
|
+
async function askForConsent() {
|
|
38
|
+
// Skip prompt if:
|
|
39
|
+
// 1. Not a TTY (CI/CD, piped input)
|
|
40
|
+
// 2. STACKMEMORY_AUTO_HOOKS=true is set
|
|
41
|
+
// 3. Running in CI environment
|
|
42
|
+
if (
|
|
43
|
+
!process.stdin.isTTY ||
|
|
44
|
+
process.env.STACKMEMORY_AUTO_HOOKS === 'true' ||
|
|
45
|
+
process.env.CI === 'true'
|
|
46
|
+
) {
|
|
47
|
+
// In non-interactive mode, skip hook installation silently
|
|
48
|
+
console.log(
|
|
49
|
+
'StackMemory installed. Run "stackmemory setup-mcp" to configure Claude Code integration.'
|
|
50
|
+
);
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
console.log('\nš¦ StackMemory Post-Install\n');
|
|
55
|
+
console.log(
|
|
56
|
+
'StackMemory can integrate with Claude Code by installing hooks that:'
|
|
57
|
+
);
|
|
58
|
+
console.log(' - Track tool usage for better context');
|
|
59
|
+
console.log(' - Enable session persistence across restarts');
|
|
60
|
+
console.log(' - Sync context with Linear (optional)');
|
|
61
|
+
console.log('\nThis will modify files in ~/.claude/\n');
|
|
62
|
+
|
|
63
|
+
return new Promise((resolve) => {
|
|
64
|
+
const rl = createInterface({
|
|
65
|
+
input: process.stdin,
|
|
66
|
+
output: process.stdout,
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
rl.question('Install Claude Code hooks? [y/N] ', (answer) => {
|
|
70
|
+
rl.close();
|
|
71
|
+
const normalized = answer.toLowerCase().trim();
|
|
72
|
+
resolve(normalized === 'y' || normalized === 'yes');
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
// Timeout after 30 seconds - default to no
|
|
76
|
+
setTimeout(() => {
|
|
77
|
+
console.log('\n(Timed out, skipping hook installation)');
|
|
78
|
+
rl.close();
|
|
79
|
+
resolve(false);
|
|
80
|
+
}, 30000);
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
30
84
|
async function installClaudeHooks() {
|
|
31
85
|
try {
|
|
32
86
|
// Create Claude hooks directory if it doesn't exist
|
|
33
87
|
if (!existsSync(claudeHooksDir)) {
|
|
34
88
|
mkdirSync(claudeHooksDir, { recursive: true });
|
|
35
|
-
console.log('
|
|
89
|
+
console.log('Created ~/.claude/hooks directory');
|
|
36
90
|
}
|
|
37
91
|
|
|
38
92
|
// Copy hook files
|
|
@@ -48,7 +102,7 @@ async function installClaudeHooks() {
|
|
|
48
102
|
if (existsSync(destPath)) {
|
|
49
103
|
const backupPath = `${destPath}.backup-${Date.now()}`;
|
|
50
104
|
copyFileSync(destPath, backupPath);
|
|
51
|
-
console.log(
|
|
105
|
+
console.log(` Backed up: ${hookFile}`);
|
|
52
106
|
}
|
|
53
107
|
|
|
54
108
|
copyFileSync(srcPath, destPath);
|
|
@@ -62,7 +116,7 @@ async function installClaudeHooks() {
|
|
|
62
116
|
}
|
|
63
117
|
|
|
64
118
|
installed++;
|
|
65
|
-
console.log(
|
|
119
|
+
console.log(` Installed: ${hookFile}`);
|
|
66
120
|
}
|
|
67
121
|
}
|
|
68
122
|
|
|
@@ -71,9 +125,8 @@ async function installClaudeHooks() {
|
|
|
71
125
|
if (existsSync(claudeConfigFile)) {
|
|
72
126
|
try {
|
|
73
127
|
hooksConfig = JSON.parse(readFileSync(claudeConfigFile, 'utf8'));
|
|
74
|
-
console.log('š Loaded existing hooks.json');
|
|
75
128
|
} catch {
|
|
76
|
-
|
|
129
|
+
// Start fresh if parse fails
|
|
77
130
|
}
|
|
78
131
|
}
|
|
79
132
|
|
|
@@ -86,21 +139,11 @@ async function installClaudeHooks() {
|
|
|
86
139
|
};
|
|
87
140
|
|
|
88
141
|
writeFileSync(claudeConfigFile, JSON.stringify(newHooksConfig, null, 2));
|
|
89
|
-
console.log('š§ Updated hooks.json configuration');
|
|
90
142
|
|
|
91
143
|
if (installed > 0) {
|
|
92
|
-
console.log(
|
|
93
|
-
|
|
94
|
-
);
|
|
95
|
-
console.log(
|
|
96
|
-
'Tool usage and session data will now be automatically logged'
|
|
97
|
-
);
|
|
98
|
-
console.log(
|
|
99
|
-
`Traces saved to: ${join(homedir(), '.stackmemory', 'traces')}`
|
|
100
|
-
);
|
|
101
|
-
console.log(
|
|
102
|
-
'\nTo disable tracing, set DEBUG_TRACE=false in your .env file'
|
|
103
|
-
);
|
|
144
|
+
console.log(`\n[OK] Installed ${installed} Claude hooks`);
|
|
145
|
+
console.log(` Traces: ~/.stackmemory/traces/`);
|
|
146
|
+
console.log(' To disable: set DEBUG_TRACE=false in .env');
|
|
104
147
|
}
|
|
105
148
|
|
|
106
149
|
// Install session daemon binary
|
|
@@ -108,10 +151,8 @@ async function installClaudeHooks() {
|
|
|
108
151
|
|
|
109
152
|
return true;
|
|
110
153
|
} catch (error) {
|
|
111
|
-
console.error('
|
|
112
|
-
console.error(
|
|
113
|
-
' This is not critical - StackMemory will still work without hooks'
|
|
114
|
-
);
|
|
154
|
+
console.error('Hook installation failed:', error.message);
|
|
155
|
+
console.error('(Non-critical - StackMemory works without hooks)');
|
|
115
156
|
return false;
|
|
116
157
|
}
|
|
117
158
|
}
|
|
@@ -154,8 +195,17 @@ async function installSessionDaemon() {
|
|
|
154
195
|
|
|
155
196
|
// Only run if called directly (not imported)
|
|
156
197
|
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
157
|
-
|
|
158
|
-
|
|
198
|
+
const consent = await askForConsent();
|
|
199
|
+
if (consent) {
|
|
200
|
+
await installClaudeHooks();
|
|
201
|
+
console.log(
|
|
202
|
+
'\nNext: Run "stackmemory setup-mcp" to complete Claude Code integration.'
|
|
203
|
+
);
|
|
204
|
+
} else {
|
|
205
|
+
console.log(
|
|
206
|
+
'Skipped hook installation. Run "stackmemory hooks install" later if needed.'
|
|
207
|
+
);
|
|
208
|
+
}
|
|
159
209
|
}
|
|
160
210
|
|
|
161
211
|
export { installClaudeHooks };
|