memoir-cli 3.1.1 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,107 @@
1
+ import chalk from 'chalk';
2
+ import boxen from 'boxen';
3
+ import gradient from 'gradient-string';
4
+ import { getSession, getSubscription } from '../cloud/auth.js';
5
+
6
+ export async function upgradeCommand() {
7
+ const session = await getSession();
8
+ let currentPlan = 'free';
9
+ let email = null;
10
+
11
+ if (session) {
12
+ email = session.user.email;
13
+ try {
14
+ const sub = await getSubscription(session);
15
+ currentPlan = sub.status === 'pro' ? 'pro' : 'free';
16
+ } catch {
17
+ // Fall through as free
18
+ }
19
+ }
20
+
21
+ // Build comparison table
22
+ const col1 = 22;
23
+ const col2 = 22;
24
+
25
+ const pad = (str, width) => {
26
+ // Strip ANSI for length calculation
27
+ const stripped = str.replace(/\u001b\[[0-9;]*m/g, '');
28
+ const diff = width - stripped.length;
29
+ return diff > 0 ? str + ' '.repeat(diff) : str;
30
+ };
31
+
32
+ const freeLabel = currentPlan === 'free' ? 'Free (current)' : 'Free';
33
+ const proLabel = currentPlan === 'pro' ? 'Pro (current)' : 'Pro $15/mo';
34
+ const teamsLabel = 'Teams $29/seat';
35
+
36
+ const header =
37
+ pad(chalk.bold.white(freeLabel), col1) +
38
+ pad(chalk.bold.cyan(proLabel), col2) +
39
+ chalk.bold.magenta(teamsLabel);
40
+
41
+ const sep = chalk.gray('─'.repeat(col1 + col2 + 18));
42
+
43
+ const rows = [
44
+ [chalk.gray('3 cloud backups'), chalk.white('50 cloud backups'), chalk.white('Unlimited backups')],
45
+ [chalk.gray('Local only'), chalk.white('Unlimited machines'), chalk.white('Shared team context')],
46
+ [chalk.gray('Manual snapshots'), chalk.white('Auto snapshots'), chalk.white('Team dashboard')],
47
+ [chalk.gray('Community support'), chalk.white('Priority support'), chalk.white('Audit log')],
48
+ [chalk.gray('—'), chalk.white('E2E encryption'), chalk.white('SSO & RBAC')],
49
+ [chalk.gray('—'), chalk.white('Version history'), chalk.white('Priority onboarding')],
50
+ ];
51
+
52
+ const tableRows = rows.map(([a, b, c]) =>
53
+ pad(a, col1) + pad(b, col2) + c
54
+ ).join('\n');
55
+
56
+ const table =
57
+ '\n' + header + '\n' +
58
+ sep + '\n' +
59
+ tableRows + '\n';
60
+
61
+ // Status line
62
+ let statusLine;
63
+ if (!session) {
64
+ statusLine = chalk.yellow('Not logged in.') + chalk.gray(' Run ') + chalk.cyan('memoir login') + chalk.gray(' first.');
65
+ } else if (currentPlan === 'pro') {
66
+ statusLine = chalk.green('You\'re on Pro!') + ' ' + chalk.gray('Teams is coming soon — join the waitlist at memoir.sh/teams');
67
+ } else {
68
+ statusLine = chalk.gray('Logged in as ') + chalk.cyan(email);
69
+ }
70
+
71
+ console.log('\n' + boxen(
72
+ gradient.pastel(' memoir upgrade ') + '\n\n' +
73
+ table + '\n' +
74
+ statusLine,
75
+ { padding: 1, borderStyle: 'round', borderColor: 'cyan', dimBorder: true }
76
+ ));
77
+
78
+ // If free and logged in, open pricing page
79
+ if (session && currentPlan === 'free') {
80
+ console.log('\n' + chalk.cyan(' Opening pricing page...') + '\n');
81
+
82
+ const { exec } = await import('child_process');
83
+ const url = 'https://memoir.sh/pricing';
84
+
85
+ const platform = process.platform;
86
+ let cmd;
87
+ if (platform === 'darwin') {
88
+ cmd = `open "${url}"`;
89
+ } else if (platform === 'win32') {
90
+ cmd = `start "${url}"`;
91
+ } else {
92
+ cmd = `xdg-open "${url}"`;
93
+ }
94
+
95
+ exec(cmd, () => {});
96
+
97
+ console.log(
98
+ chalk.gray(' Once you\'ve completed payment, run ') +
99
+ chalk.cyan('memoir login') +
100
+ chalk.gray(' to refresh your plan.') + '\n'
101
+ );
102
+ } else if (!session) {
103
+ console.log('\n' + chalk.gray(' Sign up at ') + chalk.cyan('memoir.sh/pricing') + chalk.gray(' or run ') + chalk.cyan('memoir login') + chalk.gray(' to get started.') + '\n');
104
+ } else {
105
+ console.log();
106
+ }
107
+ }
@@ -287,6 +287,83 @@ ${section}`;
287
287
  return fresh.length;
288
288
  }
289
289
 
290
+ /**
291
+ * Promote memories from project-scoped dirs to the home-level scope.
292
+ * Claude scopes memory per working directory — memories saved in ~/memoir
293
+ * are invisible from ~/btc-trader. This copies important .md files to the
294
+ * home-level scope so they're accessible from ANY directory.
295
+ *
296
+ * Only promotes files with frontmatter type: user or type: project (not ephemeral ones).
297
+ */
298
+ export function promoteMemoriesToGlobal() {
299
+ const claudeDir = path.join(home, '.claude');
300
+ const projectsDir = path.join(claudeDir, 'projects');
301
+ if (!fs.existsSync(projectsDir)) return 0;
302
+
303
+ // Find the home-level key
304
+ let homeKey;
305
+ if (process.platform === 'win32') {
306
+ homeKey = home.replace(/\\/g, '-').replace(/:/g, '-');
307
+ } else {
308
+ homeKey = '-' + home.replace(/^\//, '').replace(/\//g, '-');
309
+ }
310
+
311
+ const homeMemDir = path.join(projectsDir, homeKey, 'memory');
312
+ fs.mkdirSync(homeMemDir, { recursive: true });
313
+
314
+ const homeMemoryMdPath = path.join(homeMemDir, 'MEMORY.md');
315
+ let homeMemoryMd = '';
316
+ if (fs.existsSync(homeMemoryMdPath)) {
317
+ homeMemoryMd = fs.readFileSync(homeMemoryMdPath, 'utf8');
318
+ } else {
319
+ homeMemoryMd = '# Project Memory\n';
320
+ }
321
+
322
+ let promoted = 0;
323
+ const entries = fs.readdirSync(projectsDir, { withFileTypes: true })
324
+ .filter(e => e.isDirectory() && e.name !== homeKey);
325
+
326
+ for (const entry of entries) {
327
+ const memDir = path.join(projectsDir, entry.name, 'memory');
328
+ if (!fs.existsSync(memDir)) continue;
329
+
330
+ const files = fs.readdirSync(memDir)
331
+ .filter(f => f.endsWith('.md') && f !== 'MEMORY.md' && f !== 'handoff.md');
332
+
333
+ for (const file of files) {
334
+ const destPath = path.join(homeMemDir, file);
335
+ // Skip if already exists in home scope
336
+ if (fs.existsSync(destPath)) continue;
337
+
338
+ const content = fs.readFileSync(path.join(memDir, file), 'utf8');
339
+
340
+ // Only promote files with type: user or type: project
341
+ const typeMatch = content.match(/^type:\s*(user|project)/m);
342
+ if (!typeMatch) continue;
343
+
344
+ // Copy to home scope
345
+ fs.writeFileSync(destPath, content);
346
+
347
+ // Add to MEMORY.md if not already referenced
348
+ if (!homeMemoryMd.includes(file)) {
349
+ const nameMatch = content.match(/^name:\s*(.+)/m);
350
+ const descMatch = content.match(/^description:\s*(.+)/m);
351
+ const name = nameMatch ? nameMatch[1].trim() : file.replace('.md', '').replace(/-/g, ' ');
352
+ const desc = descMatch ? descMatch[1].trim() : '';
353
+ homeMemoryMd += `- [${name}](${file})${desc ? ' — ' + desc : ''}\n`;
354
+ }
355
+
356
+ promoted++;
357
+ }
358
+ }
359
+
360
+ if (promoted > 0) {
361
+ fs.writeFileSync(homeMemoryMdPath, homeMemoryMd);
362
+ }
363
+
364
+ return promoted;
365
+ }
366
+
290
367
  /**
291
368
  * Generate a concise handoff markdown from parsed session
292
369
  * This is what gets injected into the AI tool on the other machine
package/src/mcp.js ADDED
@@ -0,0 +1,429 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Memoir MCP Server
4
+ *
5
+ * Exposes memoir's memory management as MCP tools for Claude Code, Cursor, VS Code, etc.
6
+ * Run via: memoir mcp (or directly: node src/mcp.js)
7
+ */
8
+
9
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
10
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
11
+ import fs from 'fs-extra';
12
+ import path from 'path';
13
+ import os from 'os';
14
+ import { z } from 'zod';
15
+ import { getConfig, listProfiles, getActiveProfileName } from './config.js';
16
+ import { adapters } from './adapters/index.js';
17
+
18
+ const home = os.homedir();
19
+
20
+ // ── Helpers ──────────────────────────────────────────────────────────────────
21
+
22
+ /**
23
+ * Read all memory files from a tool adapter's source directory
24
+ */
25
+ async function readMemoryFiles(adapter) {
26
+ const files = [];
27
+
28
+ if (adapter.customExtract) {
29
+ for (const file of adapter.files) {
30
+ const filePath = path.join(adapter.source, file);
31
+ if (await fs.pathExists(filePath)) {
32
+ try {
33
+ const content = await fs.readFile(filePath, 'utf8');
34
+ files.push({ path: file, content, tool: adapter.name });
35
+ } catch {}
36
+ }
37
+ }
38
+ return files;
39
+ }
40
+
41
+ if (!(await fs.pathExists(adapter.source))) return files;
42
+
43
+ const walk = async (dir, prefix = '') => {
44
+ let entries;
45
+ try { entries = await fs.readdir(dir, { withFileTypes: true }); } catch { return; }
46
+
47
+ for (const entry of entries) {
48
+ const fullPath = path.join(dir, entry.name);
49
+ const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;
50
+
51
+ if (entry.isDirectory()) {
52
+ if (adapter.filter(fullPath)) {
53
+ await walk(fullPath, relPath);
54
+ }
55
+ } else if (entry.name.endsWith('.md') || entry.name.endsWith('.json') || entry.name.endsWith('.yml') || entry.name.endsWith('.yaml')) {
56
+ if (adapter.filter(fullPath)) {
57
+ try {
58
+ const content = await fs.readFile(fullPath, 'utf8');
59
+ files.push({ path: relPath, content, tool: adapter.name });
60
+ } catch {}
61
+ }
62
+ }
63
+ }
64
+ };
65
+
66
+ await walk(adapter.source);
67
+ return files;
68
+ }
69
+
70
+ /**
71
+ * Search across all memory files for a query (case-insensitive keyword match)
72
+ */
73
+ async function searchMemories(query) {
74
+ const results = [];
75
+ const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
76
+
77
+ for (const adapter of adapters) {
78
+ const files = await readMemoryFiles(adapter);
79
+ for (const file of files) {
80
+ const lower = file.content.toLowerCase();
81
+ const score = terms.reduce((s, t) => s + (lower.includes(t) ? 1 : 0), 0);
82
+ if (score > 0) {
83
+ results.push({ ...file, score, relevance: score / terms.length });
84
+ }
85
+ }
86
+ }
87
+
88
+ // Also search per-project AI config files
89
+ const projectFiles = ['CLAUDE.md', 'GEMINI.md', 'CHATGPT.md', '.cursorrules', '.windsurfrules', '.clinerules'];
90
+ const skipDirs = new Set(['node_modules', '.git', '.next', '.vercel', 'dist', 'build', '__pycache__', '.venv', 'venv', '.cache', 'Library', '.Trash', 'Applications', 'Downloads']);
91
+
92
+ const scanProjects = async (dir, depth = 0) => {
93
+ if (depth > 3) return;
94
+ let entries;
95
+ try { entries = await fs.readdir(dir, { withFileTypes: true }); } catch { return; }
96
+
97
+ for (const file of projectFiles) {
98
+ const filePath = path.join(dir, file);
99
+ if (await fs.pathExists(filePath)) {
100
+ try {
101
+ const content = await fs.readFile(filePath, 'utf8');
102
+ const lower = content.toLowerCase();
103
+ const score = terms.reduce((s, t) => s + (lower.includes(t) ? 1 : 0), 0);
104
+ if (score > 0) {
105
+ results.push({
106
+ path: `${path.basename(dir)}/${file}`,
107
+ content,
108
+ tool: `Project: ${path.basename(dir)}`,
109
+ score,
110
+ relevance: score / terms.length
111
+ });
112
+ }
113
+ } catch {}
114
+ }
115
+ }
116
+
117
+ for (const entry of entries) {
118
+ if (!entry.isDirectory()) continue;
119
+ if (entry.name.startsWith('.') && entry.name !== '.github') continue;
120
+ if (skipDirs.has(entry.name)) continue;
121
+ await scanProjects(path.join(dir, entry.name), depth + 1);
122
+ }
123
+ };
124
+
125
+ await scanProjects(home);
126
+
127
+ return results.sort((a, b) => b.score - a.score);
128
+ }
129
+
130
+ /**
131
+ * Get list of detected tools with status
132
+ */
133
+ async function getDetectedTools() {
134
+ const detected = [];
135
+ for (const adapter of adapters) {
136
+ let found = false;
137
+ if (adapter.customExtract) {
138
+ for (const file of adapter.files) {
139
+ if (await fs.pathExists(path.join(adapter.source, file))) { found = true; break; }
140
+ }
141
+ } else {
142
+ found = await fs.pathExists(adapter.source);
143
+ }
144
+ detected.push({ name: adapter.name, icon: adapter.icon, installed: found });
145
+ }
146
+ return detected;
147
+ }
148
+
149
+ // ── MCP Server ───────────────────────────────────────────────────────────────
150
+
151
+ const server = new McpServer({
152
+ name: 'memoir',
153
+ version: '3.2.0',
154
+ }, {
155
+ capabilities: {
156
+ tools: {},
157
+ resources: {},
158
+ }
159
+ });
160
+
161
+ // ── Tools ────────────────────────────────────────────────────────────────────
162
+
163
+ server.tool(
164
+ 'memoir_status',
165
+ 'Show which AI tools are detected on this machine and memoir configuration status',
166
+ {},
167
+ async () => {
168
+ const config = await getConfig();
169
+ const tools = await getDetectedTools();
170
+ const profile = await getActiveProfileName();
171
+ const profiles = await listProfiles();
172
+
173
+ const installed = tools.filter(t => t.installed);
174
+ const toolList = installed.map(t => ` ${t.icon} ${t.name}`).join('\n');
175
+ const notInstalled = tools.filter(t => !t.installed).map(t => t.name).join(', ');
176
+
177
+ let configStatus;
178
+ if (config) {
179
+ const dest = config.provider === 'git' ? config.gitRepo : config.localPath;
180
+ configStatus = `Connected → ${dest}`;
181
+ } else {
182
+ configStatus = 'Not configured (run: memoir init)';
183
+ }
184
+
185
+ return {
186
+ content: [{
187
+ type: 'text',
188
+ text: [
189
+ `Memoir Status`,
190
+ `─────────────`,
191
+ `Config: ${configStatus}`,
192
+ `Profile: ${profile} (${profiles.length} total)`,
193
+ `Encryption: ${config?.encrypt ? 'enabled' : 'disabled'}`,
194
+ ``,
195
+ `Detected AI Tools (${installed.length}):`,
196
+ toolList,
197
+ ``,
198
+ notInstalled.length > 0 ? `Also supports: ${notInstalled}` : '',
199
+ ].filter(Boolean).join('\n')
200
+ }]
201
+ };
202
+ }
203
+ );
204
+
205
+ server.tool(
206
+ 'memoir_recall',
207
+ 'Search across all AI tool memories, project configs, and session context for relevant information. Use this to find what you know about a topic, project, or tool.',
208
+ { query: z.string().describe('Search query — keywords or topic to find in memories') },
209
+ async ({ query }) => {
210
+ const results = await searchMemories(query);
211
+
212
+ if (results.length === 0) {
213
+ return {
214
+ content: [{ type: 'text', text: `No memories found matching "${query}".` }]
215
+ };
216
+ }
217
+
218
+ // Return top 10 results with content
219
+ const top = results.slice(0, 10);
220
+ const output = top.map((r, i) => {
221
+ const preview = r.content.length > 500 ? r.content.slice(0, 500) + '...' : r.content;
222
+ return [
223
+ `── ${i + 1}. ${r.tool} / ${r.path} (relevance: ${Math.round(r.relevance * 100)}%) ──`,
224
+ preview,
225
+ ].join('\n');
226
+ }).join('\n\n');
227
+
228
+ return {
229
+ content: [{
230
+ type: 'text',
231
+ text: `Found ${results.length} memories matching "${query}":\n\n${output}`
232
+ }]
233
+ };
234
+ }
235
+ );
236
+
237
+ server.tool(
238
+ 'memoir_remember',
239
+ 'Save a memory to a specific AI tool\'s memory files. Use this to persist important context, decisions, or facts for future sessions.',
240
+ {
241
+ content: z.string().describe('The memory content to save (markdown format)'),
242
+ filename: z.string().describe('Filename for the memory (e.g. "auth-setup.md", "project-goals.md")'),
243
+ tool: z.string().optional().describe('Which AI tool to save to: "claude", "gemini", "cursor", etc. Defaults to claude.'),
244
+ project: z.string().optional().describe('Project directory path to save a project-level memory (e.g. CLAUDE.md). If provided, saves to that project directory instead of global tool config.'),
245
+ },
246
+ async ({ content, filename, tool, project }) => {
247
+ // Project-level memory
248
+ if (project) {
249
+ const projectDir = project.startsWith('/') ? project : path.join(home, project);
250
+ if (!(await fs.pathExists(projectDir))) {
251
+ return { content: [{ type: 'text', text: `Project directory not found: ${projectDir}` }] };
252
+ }
253
+
254
+ // Default to CLAUDE.md for project-level memories
255
+ const targetFile = filename || 'CLAUDE.md';
256
+ const targetPath = path.join(projectDir, targetFile);
257
+
258
+ // Append to existing file or create new
259
+ if (await fs.pathExists(targetPath)) {
260
+ const existing = await fs.readFile(targetPath, 'utf8');
261
+ await fs.writeFile(targetPath, existing + '\n\n' + content);
262
+ } else {
263
+ await fs.writeFile(targetPath, content);
264
+ }
265
+
266
+ return {
267
+ content: [{ type: 'text', text: `Saved to ${targetPath}` }]
268
+ };
269
+ }
270
+
271
+ // Global tool memory
272
+ const toolKey = (tool || 'claude').toLowerCase();
273
+
274
+ // Find the right directory for the tool
275
+ let targetDir;
276
+ if (toolKey === 'claude') {
277
+ // Save to Claude's memory system
278
+ const claudeMemDir = path.join(home, '.claude', 'projects', '-Users-' + path.basename(home), 'memory');
279
+ await fs.ensureDir(claudeMemDir);
280
+ targetDir = claudeMemDir;
281
+ } else if (toolKey === 'gemini') {
282
+ targetDir = path.join(home, '.gemini');
283
+ } else if (toolKey === 'cursor') {
284
+ const cursorDir = process.platform === 'win32'
285
+ ? path.join(process.env.APPDATA || '', 'Cursor', 'User', 'rules')
286
+ : path.join(home, 'Library', 'Application Support', 'Cursor', 'User', 'rules');
287
+ await fs.ensureDir(cursorDir);
288
+ targetDir = cursorDir;
289
+ } else {
290
+ return { content: [{ type: 'text', text: `Unsupported tool for writing: ${toolKey}. Supported: claude, gemini, cursor` }] };
291
+ }
292
+
293
+ if (!filename.endsWith('.md')) filename += '.md';
294
+ const targetPath = path.join(targetDir, filename);
295
+ await fs.writeFile(targetPath, content);
296
+
297
+ return {
298
+ content: [{ type: 'text', text: `Memory saved to ${targetPath}` }]
299
+ };
300
+ }
301
+ );
302
+
303
+ server.tool(
304
+ 'memoir_list',
305
+ 'List all memory files across all detected AI tools and projects',
306
+ {
307
+ tool: z.string().optional().describe('Filter to a specific tool: "claude", "gemini", "cursor", etc. Leave empty for all.'),
308
+ },
309
+ async ({ tool }) => {
310
+ const allFiles = [];
311
+
312
+ for (const adapter of adapters) {
313
+ if (tool) {
314
+ const key = tool.toLowerCase();
315
+ if (!adapter.name.toLowerCase().includes(key)) continue;
316
+ }
317
+
318
+ const files = await readMemoryFiles(adapter);
319
+ for (const f of files) {
320
+ allFiles.push({ tool: adapter.name, icon: adapter.icon, path: f.path, size: f.content.length });
321
+ }
322
+ }
323
+
324
+ if (allFiles.length === 0) {
325
+ return { content: [{ type: 'text', text: tool ? `No memory files found for ${tool}.` : 'No memory files found.' }] };
326
+ }
327
+
328
+ // Group by tool
329
+ const grouped = {};
330
+ for (const f of allFiles) {
331
+ if (!grouped[f.tool]) grouped[f.tool] = [];
332
+ grouped[f.tool].push(f);
333
+ }
334
+
335
+ const output = Object.entries(grouped).map(([toolName, files]) => {
336
+ const icon = files[0]?.icon || '';
337
+ const fileList = files.map(f => {
338
+ const sizeStr = f.size < 1024 ? `${f.size}B` : `${(f.size / 1024).toFixed(1)}KB`;
339
+ return ` ${f.path} (${sizeStr})`;
340
+ }).join('\n');
341
+ return `${icon} ${toolName} (${files.length} files)\n${fileList}`;
342
+ }).join('\n\n');
343
+
344
+ return {
345
+ content: [{ type: 'text', text: `Memory files (${allFiles.length} total):\n\n${output}` }]
346
+ };
347
+ }
348
+ );
349
+
350
+ server.tool(
351
+ 'memoir_read',
352
+ 'Read the full content of a specific memory file',
353
+ {
354
+ tool: z.string().describe('Tool name: "claude", "gemini", "cursor", etc.'),
355
+ filepath: z.string().describe('Relative file path within the tool\'s memory directory'),
356
+ },
357
+ async ({ tool, filepath }) => {
358
+ const toolKey = tool.toLowerCase();
359
+ const adapter = adapters.find(a => a.name.toLowerCase().includes(toolKey));
360
+
361
+ if (!adapter) {
362
+ return { content: [{ type: 'text', text: `Unknown tool: ${tool}. Available: ${adapters.map(a => a.name).join(', ')}` }] };
363
+ }
364
+
365
+ const fullPath = path.join(adapter.source, filepath);
366
+
367
+ if (!(await fs.pathExists(fullPath))) {
368
+ return { content: [{ type: 'text', text: `File not found: ${filepath} in ${adapter.name}` }] };
369
+ }
370
+
371
+ try {
372
+ const content = await fs.readFile(fullPath, 'utf8');
373
+ return {
374
+ content: [{ type: 'text', text: `── ${adapter.name} / ${filepath} ──\n\n${content}` }]
375
+ };
376
+ } catch (err) {
377
+ return { content: [{ type: 'text', text: `Error reading file: ${err.message}` }] };
378
+ }
379
+ }
380
+ );
381
+
382
+ server.tool(
383
+ 'memoir_profiles',
384
+ 'List and manage memoir profiles (personal, work, etc.)',
385
+ {},
386
+ async () => {
387
+ const profiles = await listProfiles();
388
+ const active = await getActiveProfileName();
389
+
390
+ if (profiles.length === 0) {
391
+ return { content: [{ type: 'text', text: 'No profiles configured. Run: memoir init' }] };
392
+ }
393
+
394
+ const list = profiles.map(p => ` ${p === active ? '● ' : ' '}${p}${p === active ? ' (active)' : ''}`).join('\n');
395
+
396
+ return {
397
+ content: [{
398
+ type: 'text',
399
+ text: `Memoir Profiles:\n\n${list}\n\nSwitch with: memoir profile switch <name>`
400
+ }]
401
+ };
402
+ }
403
+ );
404
+
405
+ // ── Resources ────────────────────────────────────────────────────────────────
406
+
407
+ // Expose detected tools as browsable resources
408
+ server.resource(
409
+ 'detected-tools',
410
+ 'memoir://tools',
411
+ { description: 'List of AI tools detected on this machine', mimeType: 'text/plain' },
412
+ async () => {
413
+ const tools = await getDetectedTools();
414
+ const text = tools.map(t => `${t.icon} ${t.name}: ${t.installed ? 'installed' : 'not found'}`).join('\n');
415
+ return { contents: [{ uri: 'memoir://tools', text, mimeType: 'text/plain' }] };
416
+ }
417
+ );
418
+
419
+ // ── Start ────────────────────────────────────────────────────────────────────
420
+
421
+ async function main() {
422
+ const transport = new StdioServerTransport();
423
+ await server.connect(transport);
424
+ }
425
+
426
+ main().catch((err) => {
427
+ process.stderr.write(`Memoir MCP server error: ${err.message}\n`);
428
+ process.exit(1);
429
+ });
@@ -36,7 +36,7 @@ export async function syncToGit(config, stagingDir, spinner) {
36
36
 
37
37
  try {
38
38
  try {
39
- execFileSync('git', ['clone', '--depth', '1', repoUrl, '.'], { cwd: gitDir, stdio: 'ignore' });
39
+ execFileSync('git', ['clone', '--depth', '1', repoUrl, '.'], { cwd: gitDir, stdio: 'ignore', timeout: 60000 });
40
40
  const files = await fs.readdir(gitDir);
41
41
  for (const f of files) {
42
42
  if (f !== '.git') await fs.remove(path.join(gitDir, f));
@@ -48,20 +48,20 @@ export async function syncToGit(config, stagingDir, spinner) {
48
48
 
49
49
  await fs.copy(stagingDir, gitDir);
50
50
 
51
- execFileSync('git', ['add', '-A'], { cwd: gitDir, stdio: 'ignore' });
52
- execFileSync('git', ['config', 'user.name', 'memoir'], { cwd: gitDir, stdio: 'ignore' });
53
- execFileSync('git', ['config', 'user.email', 'bot@memoir.dev'], { cwd: gitDir, stdio: 'ignore' });
51
+ execFileSync('git', ['add', '-A'], { cwd: gitDir, stdio: 'ignore', timeout: 30000 });
52
+ execFileSync('git', ['config', 'user.name', 'memoir'], { cwd: gitDir, stdio: 'ignore', timeout: 5000 });
53
+ execFileSync('git', ['config', 'user.email', 'bot@memoir.dev'], { cwd: gitDir, stdio: 'ignore', timeout: 5000 });
54
54
 
55
55
  const timestamp = new Date().toISOString().split('T')[0];
56
56
  try {
57
- execFileSync('git', ['commit', '-m', `memoir backup ${timestamp}`], { cwd: gitDir, stdio: 'ignore' });
57
+ execFileSync('git', ['commit', '-m', `memoir backup ${timestamp}`], { cwd: gitDir, stdio: 'ignore', timeout: 30000 });
58
58
  } catch {
59
59
  spinner.succeed(chalk.green('Already up to date! ') + chalk.gray('No changes to push.'));
60
60
  return;
61
61
  }
62
62
 
63
63
  spinner.text = `Pushing data to ${chalk.cyan(repoUrl)}...`;
64
- execFileSync('git', ['push', repoUrl, 'main'], { cwd: gitDir, stdio: 'ignore' });
64
+ execFileSync('git', ['push', repoUrl, 'main'], { cwd: gitDir, stdio: 'ignore', timeout: 120000 });
65
65
 
66
66
  spinner.succeed(chalk.green('Sync complete! ') + chalk.gray('(Uploaded securely to GitHub)'));
67
67
  } catch (err) {