-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·345 lines (299 loc) · 10.5 KB
/
cli.js
File metadata and controls
executable file
·345 lines (299 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
#!/usr/bin/env node
import fs from 'fs'
import path from 'path'
import { execSync, spawn } from 'child_process'
import checkbox, { Separator } from '@inquirer/checkbox'
import select from '@inquirer/select'
// Map j/k to ↓/↑ for all inquirer prompts
const origEmit = process.stdin.emit.bind(process.stdin)
process.stdin.emit = function (event, ...args) {
if (event === 'keypress') {
const key = args[1]
if (key && !key.ctrl && !key.meta) {
if (key.name === 'j') return origEmit('keypress', undefined, { ...key, name: 'down' })
if (key.name === 'k') return origEmit('keypress', undefined, { ...key, name: 'up' })
}
}
return origEmit(event, ...args)
}
const HOME = process.env.HOME
const PROJECTS_DIR = path.join(HOME, '.claude', 'projects')
// ===== CLI args =====
const args = process.argv.slice(2)
const listOnly = args.includes('--list')
const selectAll = args.includes('--all')
const exportIdx = args.indexOf('--export')
const exportPath = exportIdx !== -1 ? args[exportIdx + 1] : null
const modelIdx = args.indexOf('--model')
const modelArg = modelIdx !== -1 ? args[modelIdx + 1] : null
const MODEL_MAP = {
sonnet: 'claude-sonnet-4-6',
opus: 'claude-opus-4-6',
haiku: 'claude-haiku-4-5-20251001',
}
const modelId = modelArg ? (MODEL_MAP[modelArg] || modelArg) : MODEL_MAP.sonnet
if (args.includes('--help') || args.includes('-h')) {
console.log(`
msync — Sync Claude Code memories
Usage:
msync Interactive select → format → clipboard
msync --list List all memories
msync --all Select all → format → clipboard
msync --export <f> Export to file
msync --model <m> Model: sonnet(default), opus, haiku
`)
process.exit(0)
}
// ===== Prompt =====
const PROMPT = `You are a memory consolidation assistant. I'll give you a set of Claude Code memories from various projects.
Your task: merge and deduplicate them into a single, clean memory document that can be imported as a Claude.ai project prompt.
## Rules:
1. Preserve the user's original words verbatim where possible
2. Deduplicate — if the same fact appears in multiple memories, keep the most detailed version
3. Group into these sections (skip empty ones):
- **Instructions**: Rules the user asked Claude to follow (tone, format, "always do X", "never do Y")
- **Identity**: Name, location, education, languages, personal details
- **Career**: Roles, companies, skills
- **Projects**: One entry per project — what it does, status, key decisions
- **Preferences**: Opinions, tastes, working style
4. Within each section, one entry per line, sorted oldest first
5. Format: \`[YYYY-MM-DD] - content\` (use \`[unknown]\` if no date)
6. Output plain text directly, do NOT wrap in code blocks or markdown fences
---
Here are the memories to process:
`
// ===== Helpers =====
function parseFrontmatter(content) {
const m = content.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)/)
if (!m) return { meta: {}, body: content }
const meta = {}
m[1].split('\n').forEach(line => {
const i = line.indexOf(':')
if (i > 0) meta[line.slice(0, i).trim()] = line.slice(i + 1).trim()
})
return { meta, body: m[2].trim() }
}
function projectName(dirName) {
const decoded = dirName.replace(/^-/, '').replace(/-/g, '/')
const home = HOME.replace(/\//g, '/')
const rel = decoded.startsWith(home.slice(1))
? '~/' + decoded.slice(home.length)
: decoded
return rel.split('/').slice(-2).join('/')
}
function projectDirFromKey(dirName) {
return '/' + dirName.replace(/^-/, '').replace(/-/g, '/')
}
function readSettings() {
try {
return JSON.parse(fs.readFileSync(path.join(HOME, '.claude', 'settings.json'), 'utf8'))
} catch { return {} }
}
/** Scan a single directory for .md memory files */
function scanMdDir(dir, project) {
if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) return []
const results = []
for (const f of fs.readdirSync(dir)) {
if (!f.endsWith('.md') || f.startsWith('.')) continue
const content = fs.readFileSync(path.join(dir, f), 'utf8')
const { meta, body } = parseFrontmatter(content)
if (!body) continue
results.push({
project,
file: f,
name: meta.name || f.replace('.md', ''),
type: meta.type || (f === 'MEMORY.md' ? 'index' : 'unknown'),
description: meta.description || '',
body
})
}
return results
}
/** Scan an agent-memory base dir (contains subdirs per agent) */
function scanAgentMemoryDir(baseDir, projectLabel) {
if (!fs.existsSync(baseDir) || !fs.statSync(baseDir).isDirectory()) return []
const results = []
for (const agent of fs.readdirSync(baseDir)) {
const agentDir = path.join(baseDir, agent)
try { if (!fs.statSync(agentDir).isDirectory()) continue } catch { continue }
const label = projectLabel ? `${projectLabel} › agent:${agent}` : `agent:${agent}`
results.push(...scanMdDir(agentDir, label))
}
return results
}
function scanMemories() {
const memories = []
const settings = readSettings()
// 1. Project auto memory (including MEMORY.md)
if (fs.existsSync(PROJECTS_DIR)) {
for (const proj of fs.readdirSync(PROJECTS_DIR)) {
const projLabel = projectName(proj)
const memDir = path.join(PROJECTS_DIR, proj, 'memory')
memories.push(...scanMdDir(memDir, projLabel))
// 2. Project-scope & local-scope subagent memories
const projPath = projectDirFromKey(proj)
memories.push(...scanAgentMemoryDir(
path.join(projPath, '.claude', 'agent-memory'), projLabel
))
memories.push(...scanAgentMemoryDir(
path.join(projPath, '.claude', 'agent-memory-local'), projLabel
))
}
}
// 3. User-scope subagent memories
memories.push(...scanAgentMemoryDir(path.join(HOME, '.claude', 'agent-memory'), null))
// 4. autoMemoryDirectory from settings
if (settings.autoMemoryDirectory) {
const customDir = settings.autoMemoryDirectory.startsWith('/')
? settings.autoMemoryDirectory
: path.join(HOME, settings.autoMemoryDirectory)
memories.push(...scanMdDir(customDir, 'custom-memory'))
}
return memories
}
// ===== Main =====
async function main() {
const memories = scanMemories()
if (memories.length === 0) {
console.log('No memories found.')
process.exit(0)
}
if (listOnly) {
console.log(`Found ${memories.length} memories:\n`)
let lastProj = ''
memories.forEach((m, i) => {
if (m.project !== lastProj) { lastProj = m.project; console.log(` \x1B[36m${lastProj}\x1B[0m`) }
console.log(` ${String(i + 1).padStart(3)}. [${m.type}] ${m.name}`)
})
return
}
let selected
if (selectAll) {
selected = memories
console.log(`Selected all ${memories.length} memories.`)
} else {
// Build choices with project separators
const choices = []
let lastProj = ''
for (const m of memories) {
if (m.project !== lastProj) {
lastProj = m.project
choices.push(new Separator(`\x1B[1m\x1B[36m${lastProj}\x1B[0m`))
}
choices.push({
name: `[${m.type}] ${m.name}`,
value: m,
checked: true,
description: m.body
})
}
selected = await checkbox({
message: `Select memories to export (${memories.length} found)`,
choices,
pageSize: 20,
theme: {
icon: {
cursor: '❯',
checked: ` \x1B[32m◉\x1B[0m`,
unchecked: ' ◯',
},
style: {
answer: v => '\n' + v.split(', ').map(s => ` · ${s}`).join('\n'),
helpTip: v => '\n' + v
}
}
})
if (selected.length === 0) {
console.log('Nothing selected.')
return
}
}
// Select summary model
let model = modelId
if (!modelArg) {
model = await select({
message: 'Select summary model',
choices: [
{ name: 'Sonnet 4.6', value: 'claude-sonnet-4-6' },
{ name: 'Opus 4.6', value: 'claude-opus-4-6' },
{ name: 'Haiku 4.5', value: 'claude-haiku-4-5-20251001' },
]
})
}
const body = selected.map((m, i) =>
`### Memory ${i + 1}: ${m.name} (${m.type}, project: ${m.project})\n\n${m.body}`
).join('\n\n---\n\n')
// Spinner while waiting for first output
const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
let frame = 0
const spinner = setInterval(() => {
process.stdout.write(`\r\x1B[2m${frames[frame++ % frames.length]} Formatting ${selected.length} memories with ${model}...\x1B[0m`)
}, 80)
try {
const result = await new Promise((resolve, reject) => {
const child = spawn('claude', [
'-p', '--no-session-persistence',
'--model', model,
'--output-format', 'stream-json',
'--include-partial-messages',
'--verbose',
], { stdio: ['pipe', 'pipe', 'pipe'] })
let output = ''
let started = false
let buf = ''
child.stdout.on('data', chunk => {
buf += chunk.toString()
const lines = buf.split('\n')
buf = lines.pop()
for (const line of lines) {
if (!line) continue
try {
const evt = JSON.parse(line)
if (evt.type === 'stream_event' && evt.event?.delta?.type === 'text_delta') {
if (!started) {
clearInterval(spinner)
process.stdout.write('\r\x1B[2K\n')
started = true
}
const text = evt.event.delta.text
output += text
process.stdout.write(text)
}
} catch {}
}
})
let stderr = ''
child.stderr.on('data', chunk => { stderr += chunk.toString() })
child.on('close', code => {
if (!started) { clearInterval(spinner); process.stdout.write('\r\x1B[2K') }
if (code !== 0) reject(new Error(stderr || `claude exited with code ${code}`))
else resolve(output)
})
child.on('error', reject)
child.stdin.write(PROMPT + body)
child.stdin.end()
})
if (exportPath) {
const resolved = path.resolve(exportPath)
fs.writeFileSync(resolved, result)
console.log(`\nExported to ${resolved}`)
} else {
try {
execSync('pbcopy', { input: result })
console.log('\n\n✓ Copied to clipboard.')
} catch {
// non-macOS, skip
}
}
} catch (err) {
clearInterval(spinner)
process.stdout.write('\r\x1B[2K')
console.error('Claude error:', err.message)
process.exit(1)
}
}
main().catch(err => {
if (err.name === 'ExitPromptError') process.exit(0)
console.error(err)
process.exit(1)
})