macro-memory 0.9.1 → 0.26.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +157 -268
  2. package/bin/macro-memory.mjs +524 -5
  3. package/docs/CHANGELOG.md +1101 -0
  4. package/docs/MAC.md +44 -6
  5. package/lib/core/client.js +56 -22
  6. package/lib/core/config.js +15 -2
  7. package/lib/core/daemon.js +336 -0
  8. package/lib/core/engine.js +7 -6
  9. package/lib/core/fence.js +1 -1
  10. package/lib/core/serve.js +37 -14
  11. package/lib/core/trust.js +6 -2
  12. package/lib/index.js +209 -3
  13. package/lib/macro/contract.js +31 -1
  14. package/lib/macro/defs/admin.js +4 -4
  15. package/lib/macro/defs/link.js +96 -9
  16. package/lib/macro/defs/read.js +11 -1
  17. package/lib/macro/defs/remember.js +89 -1
  18. package/lib/macro/defs/search.js +157 -6
  19. package/lib/macro/dreamledger.js +6 -1
  20. package/lib/macro/evidence.js +84 -0
  21. package/lib/macro/fakesites.js +93 -0
  22. package/lib/macro/fusion.js +16 -2
  23. package/lib/macro/linkflow.js +130 -5
  24. package/lib/macro/links.js +69 -0
  25. package/lib/macro/platform.js +74 -0
  26. package/lib/macro/portability.js +737 -0
  27. package/lib/macro/prompt.js +6 -6
  28. package/lib/macro/revisions.js +3 -13
  29. package/lib/macro/slots.js +252 -0
  30. package/lib/macro/snapshot.js +309 -1
  31. package/lib/macro/tools.js +49 -4
  32. package/lib/macro/topicpages.js +300 -0
  33. package/lib/rerank/download.js +68 -0
  34. package/lib/rerank/provider.js +507 -0
  35. package/lib/rerank/runtime.js +246 -0
  36. package/lib/rerank/tokenizer.js +183 -0
  37. package/lib/semantic/download.js +68 -0
  38. package/lib/semantic/provider.js +205 -0
  39. package/lib/semantic/runtime.js +175 -0
  40. package/lib/semantic/tokenizer.js +169 -0
  41. package/package.json +1 -1
  42. package/vendor/VENDOR.json +4 -4
  43. package/vendor/dsh-memory-nebula/lib/host/adapters/meow.js +7 -1
  44. package/vendor/dsh-memory-nebula/lib/host/graph.js +183 -3
  45. package/vendor/dsh-memory-nebula/lib/index.js +75 -3
  46. package/vendor/dsh-memory-nebula/lib/web/app.js +5 -0
  47. package/vendor/dsh-memory-nebula/lib/web/i18n.js +1 -0
  48. package/vendor/meow-memory/lib/index.js +3205 -167
  49. package/vendor/meow-memory/lib/prompts/en/labels.md +2 -0
  50. package/vendor/meow-memory/lib/prompts/en/tools.md +1 -0
  51. package/vendor/meow-memory/lib/prompts/pt-br/labels.md +2 -0
  52. package/vendor/meow-memory/lib/prompts/pt-br/tools.md +1 -0
  53. package/vendor/meow-memory/lib/prompts/zh/labels.md +2 -0
  54. package/vendor/meow-memory/lib/prompts/zh/tools.md +1 -0
@@ -10,7 +10,16 @@
10
10
  * macro-memory read <id> 读一条
11
11
  * macro-memory project <名字> 项目全景
12
12
  * macro-memory injection 看常驻注入文本(L0)
13
- * macro-memory doctor 自检:引擎、库、信任、路径
13
+ * macro-memory snapshot list 列出库快照(时间、大小、条数、与现库的差)
14
+ * macro-memory snapshot now 手动打一份快照
15
+ * macro-memory snapshot diff [s] 某份快照与现库逐项比
16
+ * macro-memory snapshot restore s 还原方案(默认只打印,--apply=<stamp> 才真做)
17
+ * macro-memory doctor 自检:引擎、库、信任、路径、四种假现场
18
+ * macro-memory serve 前台单写者服务(Ctrl-C 停)
19
+ * macro-memory serve --install-agent 装成用户级后台服务(launchd / systemd --user / 计划任务)
20
+ * macro-memory serve --uninstall-agent 卸掉后台服务(只删服务定义,不碰记忆库)
21
+ * macro-memory serve --install-agent --dry-run 只打印服务文件与命令,不写盘
22
+ * macro-memory ui --open 起管理界面并交给系统默认浏览器
14
23
  * macro-memory stats 库规模与工具清单
15
24
  *
16
25
  * 设计约束:只依赖 node 内置;不写任何全局状态;每条命令结束都关库、退出码明确
@@ -22,6 +31,9 @@ import path from 'node:path'
22
31
  import process from 'node:process'
23
32
  import { fileURLToPath } from 'node:url'
24
33
 
34
+ // 平台相关的动作(打开浏览器、mac 提醒)都从这一处问,不在命令里直接读宿主
35
+ import { browserOpenSpec, isMac } from '../lib/macro/platform.js'
36
+
25
37
  const HERE = path.dirname(fileURLToPath(import.meta.url))
26
38
  const PKG_ROOT = path.resolve(HERE, '..')
27
39
 
@@ -57,7 +69,13 @@ const HELP = `macro-memory —— 一套记忆,所有 agent
57
69
  detach 退出共享:删发现文件,回到直连(服务本身不动)
58
70
  share 看共享状态:谁是写者、队列多长、服务在不在
59
71
  ui 开管理界面(只听 127.0.0.1,一次性令牌放 URL,关掉就消失)
60
- doctor 自检:引擎就绪、库位置、信任状态、路径
72
+ snapshot list 列出库快照:时间、大小、条数、与现库的差
73
+ snapshot now 手动打一份快照(库里没变时不会重复存)
74
+ snapshot diff [s] 某份快照与现库逐项比:之后新写几条、退回去会带回来几条
75
+ snapshot restore s 还原方案。默认只打印(一个字节不写);--apply=<s> 才真做
76
+ export 导出记忆:--format=jsonl|md --to=<文件>(不给 --to 就打到屏幕)
77
+ import <文件> 导入 JSONL:默认只预览;--apply=<印> 才真写,同 id 默认跳过
78
+ doctor 自检:引擎就绪、库位置、信任状态、路径、四种假现场
61
79
  stats 库规模与工具清单
62
80
 
63
81
  通用参数:
@@ -68,6 +86,15 @@ const HELP = `macro-memory —— 一套记忆,所有 agent
68
86
  --json 机器可读输出
69
87
  --no-nebula 不挂星图引擎(更快、更省内存)
70
88
  --file <路径> 改哪个文件(默认 AGENTS.md;可给多次或逗号分隔)
89
+ --format <格式> export 用:jsonl(可导回)/ md(给人读),默认 jsonl
90
+ --to <文件> export 写到哪;不给就打屏幕(配合 > 重定向也行)
91
+ --from <文件> import 从哪读(也可以直接写在命令后面)
92
+ --status <状态> export 只导某一类:all(默认)/ active / stale / archived
93
+ --level <层> export 只要某几层(逗号分隔,如 fact,lesson)
94
+ --project <项目> export 只要某个项目
95
+ --no-links export 不带星图手工连线
96
+ --overwrite import 时同 id 已存在就替换(默认跳过)
97
+ --apply=<印> import 真写(印来自预览那一步;裸 --apply 不认)
71
98
  --port <端口> serve 监听端口(默认 0 = 系统挑一个,写进 serve.json)
72
99
  --agent <名字> attach 时自报的名字(同一份库靠它区分谁写的)
73
100
  --version 只打版本号就退出(脚本里判断装的是哪一版)
@@ -182,13 +209,29 @@ async function cmdMcp(args) {
182
209
  await eng.close()
183
210
  process.exit(2)
184
211
  }
212
+ // [0.16.0 · W2 / §2.2 B 第 4 条] 起服务时把「连的是哪个库」说出来。
213
+ // `mcp serve` 落回 process.cwd() 的时候,用户看到的现象是「我的记忆丢了」,
214
+ // 而这条路径一路不报错——所以至少要留一行字,让人能自己看出连错了地方。
215
+ // **只警告,不改行为**:故意在空目录里跑是合法用法,硬拦反而挡住正当场景。
216
+ const ws = cwdOf(args)
217
+ const { judgeMcpWorkspace } = await import('../lib/macro/fakesites.js')
218
+ const { existsSync } = await import('node:fs')
219
+ const { join } = await import('node:path')
220
+ const call = judgeMcpWorkspace({
221
+ workspace: ws,
222
+ isGit: existsSync(join(ws, '.git')),
223
+ hasDsh: existsSync(join(ws, '.dsh')),
224
+ hasDocs: existsSync(join(ws, 'docs')),
225
+ })
226
+ process.stderr.write(`macro-memory:MCP 工作区 ${ws}\n`)
227
+ if (call.level !== 'PASS') process.stderr.write(`${call.level} ${call.why}\n`)
185
228
  await serveStdio({
186
229
  engine: eng,
187
230
  version: readVersion(),
188
231
  name: 'macro-memory',
189
232
  // 宿主不会在 tools/call 里带 cwd,所以把 --cwd / MACRO_MEMORY_WORKSPACE 的结论
190
233
  // 作为默认工作区交下去;否则库会落在 MCP 子进程的 process.cwd()(宿主临时目录)里。
191
- cwd: cwdOf(args),
234
+ cwd: ws,
192
235
  log: (m) => process.stderr.write(`${m}\n`),
193
236
  })
194
237
  }
@@ -423,6 +466,401 @@ async function cmdInjection(args) {
423
466
  await eng.close()
424
467
  }
425
468
 
469
+ /**
470
+ * `snapshot` 四门(W2 / 0.16.0):list / now / diff / restore。
471
+ *
472
+ * 为什么单开一个命令组而不是塞进 doctor:doctor 是「我这套装得好不好」的体检,快照是
473
+ * 「我的数据还在不在、退得回哪一天」的账。**事故现场最先要的是后者**,而 0.15.0 之前
474
+ * 这一层做得再扎实,CLI 18 个命令里一个入口都没有——等于没有。
475
+ *
476
+ * 三条硬规矩:
477
+ * ① **不写新的快照逻辑**,全部走 `lib/macro/snapshot.js` 的既有导出。两份实现一定漂(0.2.35)。
478
+ * ② `restore` **默认一个字节不写**;真动手必须 `--apply=<stamp>`,stamp 要能和盘上那份对上
479
+ * (抄文件名、抄全路径、抄 `20261128-101820` 都认,见 `pickByStamp`)。裸 `--apply` 直接顶回去。
480
+ * ③ `restore` 自己不复制文件、不删 `-wal`/`-shm`:那三件事在 Windows 上要停进程,必须由一个
481
+ * 看着库的人做。这里只把方案算清楚 + 给一行现成命令(`tools/restore-live-db.mjs`)。
482
+ */
483
+ async function cmdSnapshot(args) {
484
+ const sub = String(args._.shift() ?? '').trim()
485
+ const S = await import('../lib/macro/snapshot.js')
486
+ const cwd = cwdOf(args)
487
+ const dir = typeof args['project-dir'] === 'string' && args['project-dir'].trim() !== '' ? args['project-dir'] : '.dsh-meow'
488
+ const json = args.json === true
489
+ // 每个子命令都要收口:把引擎的连接关掉,别让 CLI 变成一个握着库的僵尸进程。
490
+ const bye = async (code = 0) => {
491
+ try {
492
+ const Meow = await import('../vendor/meow-memory/lib/index.js')
493
+ Meow.closeAllDbs?.()
494
+ } catch {
495
+ /* 关不掉不影响退出码 */
496
+ }
497
+ process.exit(code)
498
+ }
499
+
500
+ if (sub === '' || sub === 'help') {
501
+ out([
502
+ 'macro-memory snapshot —— 库快照(记忆库被写坏时的退路)',
503
+ '',
504
+ ' snapshot list 列出快照:时间、大小、条数、与现库的差',
505
+ ' snapshot now 手动打一份(库里没变、或距上一份不足间隔时不重复存)',
506
+ ' snapshot diff [stamp] 某份与现库逐项比(默认最新那份读得动的)',
507
+ ' snapshot restore <stamp> 只打印还原方案,一个字节不写',
508
+ ' snapshot restore <stamp> --apply=<stamp> 真做(要退出 DSH 后再跑)',
509
+ '',
510
+ 'stamp 抄哪一种都认:memory-20261128-101820.db / 全路径 / 20261128-101820。',
511
+ ].join('\n'))
512
+ return bye(0)
513
+ }
514
+
515
+ if (!S.sqliteAvailable()) {
516
+ out(`这台机器的 Node 没有内置 node:sqlite,快照这一层用不了(记忆读写不受影响):${S.sqliteReason()}`)
517
+ return bye(2)
518
+ }
519
+
520
+ if (sub === 'list') {
521
+ const list = S.listSnapshots(cwd)
522
+ const keep = S.SNAPSHOT_KEEP
523
+ let cmp
524
+ try {
525
+ cmp = S.compareWithLive({ workspace: cwd, dir })
526
+ } catch {
527
+ cmp = undefined
528
+ }
529
+ if (json) {
530
+ out(JSON.stringify({ workspace: cwd, dir, count: list.length, keep, items: list.map((x) => ({ name: x.name, bytes: x.bytes, at: x.at, stamp: x.stamp })), compare: cmp === undefined ? null : { status: cmp.status, added: cmp.added?.total ?? 0, removed: cmp.removed?.total ?? 0 } }, null, 2))
531
+ return bye(0)
532
+ }
533
+ const lines = [`快照(${list.length} 份,最多留 ${keep} 份)· 工作区 ${cwd}`]
534
+ if (list.length === 0) {
535
+ lines.push(' 一份都没有。库第一次变动后会在下一轮自动存;要现在存:macro-memory snapshot now')
536
+ out(lines.join('\n'))
537
+ return bye(0)
538
+ }
539
+ for (const line of S.compareLines(cmp, { stamp: S.humanStamp(list[0].stamp) })) lines.push(line)
540
+ if (Array.isArray(cmp?.skipped) && cmp.skipped.length > 0) {
541
+ lines.push(` 另有 ${cmp.skipped.length} 份读不出来(退的时候别选):${cmp.skipped.map((x) => x.name).join(' / ')}`)
542
+ }
543
+ lines.push('')
544
+ for (const item of list) {
545
+ const bad = Array.isArray(cmp?.skipped) && cmp.skipped.some((x) => x.file === item.file)
546
+ lines.push(` ${S.humanStamp(item.stamp)} ${S.humanBytes(item.bytes).padStart(8)} ${item.name}${bad ? ' ← 读不出来' : ''}`)
547
+ }
548
+ lines.push('', '退一份回去:macro-memory snapshot restore <stamp>(先看方案,不加 --apply 不会动盘)')
549
+ out(lines.join('\n'))
550
+ return bye(0)
551
+ }
552
+
553
+ if (sub === 'now') {
554
+ const before = S.listSnapshots(cwd).length
555
+ const r = S.takeSnapshot({ workspace: cwd, dir, force: args.force === true })
556
+ if (json) {
557
+ out(JSON.stringify(r, null, 2))
558
+ return bye(r.status === 'error' ? 2 : 0)
559
+ }
560
+ const why = {
561
+ taken: `已存:${r.file}(${S.humanBytes(r.bytes)}${r.removed > 0 ? `,顺手清掉 ${r.removed} 份旧的` : ''})`,
562
+ fresh:
563
+ r.skipped === 'unchanged'
564
+ ? `库里没变,与最新一份是同一份,这次没多存:${r.file}(要强制存一份加 --force)`
565
+ : r.skipped === 'gap'
566
+ ? `距上一份不足 ${Math.round(S.SNAPSHOT_GAP_MS / 60000)} 分钟,这次没多存:${r.file}(要强制存一份加 --force)`
567
+ : `这一秒已经存过了,这次没多存:${r.file}`,
568
+ 'no-db': '这个工作区还没有记忆库——没有可快照的东西。',
569
+ 'no-ws': '拿不到工作区。',
570
+ error: `没存成:${r.error}`,
571
+ }[r.status] ?? `没存成:${r.status}`
572
+ out(`${why}\n(盘上共 ${before} → ${S.listSnapshots(cwd).length} 份)`)
573
+ return bye(r.status === 'error' ? 2 : 0)
574
+ }
575
+
576
+ if (sub === 'diff') {
577
+ const want = String(args._[0] ?? '').trim()
578
+ let cmp
579
+ if (want === '') {
580
+ cmp = S.compareWithLive({ workspace: cwd, dir })
581
+ } else {
582
+ const picked = S.pickByStamp(cwd, want)
583
+ if (picked.status === 'no-snapshot') {
584
+ out('一份快照都没有——没有可比的。跑 macro-memory snapshot now 存一份。')
585
+ return bye(1)
586
+ }
587
+ if (picked.status === 'no-match') {
588
+ out(`盘上没有对得上「${want}」的快照。现有:\n${picked.list.map((x) => ` ${x.name}`).join('\n')}`)
589
+ return bye(1)
590
+ }
591
+ cmp = S.compareWithLive({ workspace: cwd, dir, file: picked.item.file })
592
+ }
593
+ if (json) {
594
+ out(JSON.stringify(cmp, null, 2))
595
+ return bye(cmp.status === 'ok' ? 0 : 1)
596
+ }
597
+ const lines = []
598
+ if (cmp.status === 'no-snapshot') {
599
+ out('一份快照都没有——没有可比的。')
600
+ return bye(1)
601
+ }
602
+ const stamp = cmp.file === undefined ? '' : S.humanStamp(
603
+ (S.listSnapshots(cwd).find((x) => x.file === cmp.file) ?? { stamp: 0 }).stamp,
604
+ )
605
+ for (const line of S.compareLines(cmp, { stamp })) lines.push(line.replace(/^ {2}· /, ''))
606
+ if (lines.length === 0) lines.push(`没比成:${cmp.status}`)
607
+ if (cmp.status === 'ok') {
608
+ lines.push('', `之后新写 ${cmp.added.total} 条、快照有现库没有 ${cmp.removed.total} 条。`)
609
+ }
610
+ out(lines.join('\n'))
611
+ return bye(cmp.status === 'ok' ? 0 : 1)
612
+ }
613
+
614
+ if (sub === 'restore') {
615
+ const want = String(args._[0] ?? '').trim()
616
+ // `--apply` 的三种形态先摊开说清楚(P11):不写、写错、不带参数。
617
+ // `--apply` 后面跟一个不以 `-` 开头的值 → parseArgv 收成字符串;裸 `--apply` → true。
618
+ const applyWant = typeof args.apply === 'string' ? args.apply.trim() : ''
619
+ if (args.apply === true && !json) {
620
+ out([
621
+ '不接受裸 --apply。',
622
+ '',
623
+ '还原要停进程、覆盖活库、删 -wal/-shm——这三件事只靠「一条命令」分不开手滑和有意。',
624
+ '所以要么不给 --apply(只看方案,一个字节不写),要么把它抄全:',
625
+ '',
626
+ ' macro-memory snapshot restore <stamp> --apply=<stamp>',
627
+ '',
628
+ `例如:macro-memory snapshot restore ${String(args._[0] ?? '').trim() || '<stamp>'} --apply=${String(args._[0] ?? '').trim() || '<stamp>'}`,
629
+ ].join('\n'))
630
+ return bye(1)
631
+ }
632
+ const plan = S.restorePlan({ workspace: cwd, dir, stamp: want })
633
+ if (json && args.apply !== true && applyWant === '') {
634
+ out(JSON.stringify(plan, null, 2))
635
+ return bye(plan.status === 'ok' ? 0 : 1)
636
+ }
637
+ if (plan.status === 'no-snapshot') {
638
+ out('一份快照都没有——没有能退的东西。')
639
+ return bye(1)
640
+ }
641
+ if (plan.status === 'no-match') {
642
+ // 空 stamp 与「抄错了」分开说:前者是没指定,后者是抄错/那份已经不在了。
643
+ if (plan.want === '') {
644
+ out(
645
+ `要指定退哪一份。现有:\n${plan.list.map((x) => ` ${x.name}`).join('\n')}\n\n例:macro-memory snapshot restore ${plan.list[0]?.name ?? '<stamp>'}`,
646
+ )
647
+ } else {
648
+ out(`盘上没有对得上「${plan.want}」的快照。现有:\n${plan.list.map((x) => ` ${x.name}`).join('\n')}`)
649
+ }
650
+ return bye(1)
651
+ }
652
+ if (plan.status === 'bad-source') {
653
+ out(`那一份读不出来(${plan.error})——别退它。换一份:macro-memory snapshot list`)
654
+ return bye(1)
655
+ }
656
+ const target = plan.item
657
+ const lines = []
658
+ lines.push(`还原方案(${applyWant === '' ? '只看不动' : '要真做'})`)
659
+ lines.push(` 源快照: ${target.file}`)
660
+ lines.push(` 快照时刻:${S.humanStamp(target.stamp)}(${S.humanBytes(target.bytes)})`)
661
+ lines.push(` 现库: ${plan.live.path === '' ? '(路径取不到)' : plan.live.path}`)
662
+ lines.push(
663
+ ` ${plan.live.exists ? `${S.humanBytes(plan.live.bytes)} · ${plan.live.total} 条(${S.levelTally(plan.live.byLevel) || '空'})` : '还没有库'}`,
664
+ )
665
+ if (plan.status === 'empty-source') {
666
+ lines.push('')
667
+ lines.push(`**这一份里一条记忆都没有**(空 schema / 坏库)——退它等于把现库 ${plan.live.total} 条全清掉。`)
668
+ lines.push('别退这一份。snapshot list 里选别的,或先查为什么会出现空壳。')
669
+ out(lines.join('\n'))
670
+ return bye(1)
671
+ }
672
+ lines.push(
673
+ ` 快照里: ${plan.snapshot.total} 条(${S.levelTally(plan.snapshot.byLevel)})${plan.integrity === 'ok' ? ' · integrity_check 通过' : plan.integrity === '' ? '' : ` · integrity_check:${plan.integrity}`}`,
674
+ )
675
+ if (plan.others.length > 0) {
676
+ lines.push(` 同一时刻还有 ${plan.others.length} 份(这次选的是最新那份;要别的请抄全名):${plan.others.map((x) => x.name).join(' / ')}`)
677
+ }
678
+ if (plan.sidecars.length > 0) lines.push(` 会先删: ${plan.sidecars.join('、')}(留着会被回放,把退回去的库又带歪)`)
679
+ lines.push('')
680
+ lines.push('要做的事(按顺序,中途别开 DSH):')
681
+ lines.push(' 1) 完全退出 DSH(Windows 下这一步省不得:进程握着库,覆盖会失败或写出半个库)')
682
+ lines.push(` 2) 备份现状:${plan.live.path} 连同 -wal / -shm 复制到别处`)
683
+ lines.push(` 3) 拷回快照:${target.file} → ${plan.live.path}`)
684
+ if (plan.sidecars.length > 0) lines.push(` 4) 删掉旧日志:${plan.sidecars.join('、')}`)
685
+ lines.push(' 5) 起 DSH,数一遍:记忆条数应等于上面「快照里」那个数')
686
+ lines.push('')
687
+ lines.push(
688
+ `现成脚本(做了 2–4 步 + 自检):node tools/restore-live-db.mjs --source "${target.file}"${applyWant === '' ? ' --dry-run' : ''}`,
689
+ )
690
+
691
+ if (applyWant === '') {
692
+ lines.push('')
693
+ lines.push(`真要退,把它抄一遍:--apply=${target.name}`)
694
+ out(lines.join('\n'))
695
+ return bye(0)
696
+ }
697
+
698
+ // ── 真做:先核「抄的那一份」与「算方案的那一份」是同一份 ─────────────────
699
+ if (applyWant !== target.name && applyWant !== target.file) {
700
+ lines.push('')
701
+ lines.push(`--apply=${applyWant} 与方案里的「${target.name}」不是同一份。抄错等于退错库,这次不动。`)
702
+ out(lines.join('\n'))
703
+ return bye(1)
704
+ }
705
+ lines.push('')
706
+ lines.push('上面这些是方案,本进程到此为止——**覆盖活库不在这里做**。')
707
+ lines.push('理由:Windows 上要停进程、删 -wal/-shm,得由一个看着库的人执行;本命令只把方案算准。')
708
+ lines.push('把上面「现成脚本」那一行里去掉 --dry-run,跑它即可(它会先备份三件套再动手)。')
709
+ out(lines.join('\n'))
710
+ return bye(0)
711
+ }
712
+
713
+ out(`snapshot 没有这个子命令:${sub}\n\n 可选:list / now / diff / restore`)
714
+ return bye(1)
715
+ }
716
+
717
+ /**
718
+ * `export`(0.18.0 · W4):把记忆导出成能带走、能导回来的东西。
719
+ *
720
+ * 三条硬规矩:
721
+ * ① 逻辑全在 `lib/macro/portability.js`,CLI 只做参数与回执——两份实现一定漂。
722
+ * ② `--to` 不给就把正文打到 stdout(可以 `> file`),摘要走 stderr:
723
+ * 混在一起会毁掉重定向出来的文件。
724
+ * ③ 敏感信息**只提示**,不改正文、不阻断导出:这是出口处的提醒,不是审查。
725
+ */
726
+ async function cmdExport(args) {
727
+ const P = await import('../lib/macro/portability.js')
728
+ const cwd = cwdOf(args)
729
+ const dir = typeof args['project-dir'] === 'string' && args['project-dir'].trim() !== '' ? args['project-dir'] : '.dsh-meow'
730
+ const format = String(args.format ?? 'jsonl').trim().toLowerCase()
731
+ if (format !== 'jsonl' && format !== 'md') {
732
+ out(`--format 只认 jsonl / md,收到 ${format}`)
733
+ process.exit(1)
734
+ }
735
+ const status = String(args.status ?? 'all').trim()
736
+ if (!['all', 'active', 'stale', 'archived'].includes(status)) {
737
+ out(`--status 只认 all / active / stale / archived,收到 ${status}`)
738
+ process.exit(1)
739
+ }
740
+ const levels = typeof args.level === 'string'
741
+ ? args.level.split(',').map((s) => s.trim()).filter((s) => s !== '')
742
+ : undefined
743
+ const project = typeof args.project === 'string' ? args.project : ''
744
+ const r = P.exportMemories({
745
+ workspace: cwd,
746
+ dir,
747
+ format,
748
+ status,
749
+ ...(levels === undefined ? {} : { levels }),
750
+ project,
751
+ withLinks: args['no-links'] !== true,
752
+ })
753
+ if (!r.exists) {
754
+ out(`这个工作区还没有记忆库:${r.dbPath}\n(先 remember 一条,或确认 --cwd 指对了)`)
755
+ process.exit(1)
756
+ }
757
+ const to = typeof args.to === 'string' ? args.to : (typeof args._[0] === 'string' ? args._[0] : '')
758
+ const saved = to === '' ? null : P.writeExportFile(to, r.text)
759
+ const layers = Object.entries(r.byLevel).map(([k, v]) => `${k} ${v}`).join(' / ') || '空'
760
+ const summary = [
761
+ `导出(${format})· 工作区 ${cwd}`,
762
+ ` 库: ${r.dbPath}`,
763
+ ` 条目: ${r.entries} 条${status === 'all' ? '' : `(只导 ${status})`} · ${layers}`,
764
+ ` 连线: ${r.links} 条${r.linkError ? `(星图读不了:${r.linkError})` : ''}`,
765
+ ` 内容: ${r.bytes.toLocaleString('en-US')} B${saved ? ` → ${saved.file}` : '(打到屏幕)'}`,
766
+ P.sensitiveReport(r.sensitive, r.text.split('\n').length),
767
+ ]
768
+ if (format === 'jsonl') summary.push(` 导回来: macro-memory import ${saved ? saved.file : '<文件>'}(先预览,再 --apply=<印>)`)
769
+ if (args.json === true) {
770
+ out(JSON.stringify({
771
+ workspace: cwd,
772
+ dbPath: r.dbPath,
773
+ format,
774
+ status,
775
+ entries: r.entries,
776
+ byLevel: r.byLevel,
777
+ links: r.links,
778
+ linkError: r.linkError,
779
+ bytes: r.bytes,
780
+ file: saved === null ? null : saved.file,
781
+ sensitive: r.sensitive,
782
+ }, null, 2))
783
+ } else if (saved === null) {
784
+ // 正文 → stdout,摘要 → stderr:重定向出来的文件里只有正文。
785
+ process.stdout.write(r.text.endsWith('\n') || r.text === '' ? r.text : `${r.text}\n`)
786
+ process.stderr.write(`${summary.join('\n')}\n`)
787
+ } else {
788
+ out(summary.join('\n'))
789
+ }
790
+ }
791
+
792
+ /**
793
+ * `import`(0.18.0 · W4):把导出的 JSONL 装回去。
794
+ *
795
+ * 默认 dry-run:只算「会写几条、会跳过几条」,一个字节不动。
796
+ * 真写要 `--apply=<印>`:印 = sha256(文件内容 + 目标库路径) 前 8 位,换文件或换库都会变。
797
+ * 裸 `--apply` 一律顶回去(§2.4 的既有范式)。
798
+ */
799
+ async function cmdImport(args) {
800
+ const P = await import('../lib/macro/portability.js')
801
+ const cwd = cwdOf(args)
802
+ const dir = typeof args['project-dir'] === 'string' && args['project-dir'].trim() !== '' ? args['project-dir'] : '.dsh-meow'
803
+ const file = String(args.from ?? args._[0] ?? '').trim()
804
+ if (file === '') {
805
+ out('import 要一个文件:macro-memory import <文件.jsonl>')
806
+ process.exit(1)
807
+ }
808
+ if (args.apply === true) {
809
+ out('裸 --apply 不认:先跑一次预览,把回执里的 --apply=<印> 整行抄过来。')
810
+ process.exit(1)
811
+ }
812
+ const text = P.readImportFile(file)
813
+ const dryRun = args['dry-run'] === true || args.apply === undefined
814
+ const r = P.importJsonl({
815
+ workspace: cwd,
816
+ dir,
817
+ text,
818
+ overwrite: args.overwrite === true,
819
+ dryRun,
820
+ apply: typeof args.apply === 'string' ? args.apply : '',
821
+ })
822
+ if (args.json === true) {
823
+ out(JSON.stringify(r, null, 2))
824
+ process.exit(r.status === 'error' ? 2 : r.status === 'invalid' || r.status === 'need-apply' || r.status === 'empty' ? 1 : 0)
825
+ }
826
+ if (r.status === 'invalid') {
827
+ const lines = [`文件没通过校验:${r.invalid.length} 行有问题,整批不写`, '']
828
+ for (const bad of r.invalid.slice(0, 12)) lines.push(` 第 ${bad.line} 行:${bad.why}`)
829
+ if (r.invalid.length > 12) lines.push(` 另有 ${r.invalid.length - 12} 行没逐条列出`)
830
+ out(lines.join('\n'))
831
+ process.exit(1)
832
+ }
833
+ if (r.status === 'need-apply') {
834
+ out(`${r.why}\n\n预览结果:会写 ${r.wouldInsert ?? '?'} 条,跳过 ${r.skipped} 条(同 id 已存在)`)
835
+ process.exit(1)
836
+ }
837
+ if (r.status === 'empty') {
838
+ out(r.why)
839
+ process.exit(1)
840
+ }
841
+ if (r.status === 'error') {
842
+ out(`没导成:${r.why}`)
843
+ process.exit(2)
844
+ }
845
+ if (r.status === 'dry-run') {
846
+ out([
847
+ `预览:${r.entries} 条待导入 · ${r.dbPath}`,
848
+ ` 会写: ${r.wouldInsert ?? '?'} 条`,
849
+ ` 会跳过: ${r.skipped} 条${r.skipped > 0 ? `(同 id 已经在库里${args.overwrite === true ? '' : ';要替换加 --overwrite'})` : ''}`,
850
+ ` 印: ${r.stamp}`,
851
+ '',
852
+ `真写:macro-memory import "${file}" --apply=${r.stamp}`,
853
+ ].join('\n'))
854
+ process.exit(0)
855
+ }
856
+ out([
857
+ `导入完成:写进 ${r.inserted} 条 · 跳过 ${r.skipped} 条${r.replaced > 0 ? ` · 替换 ${r.replaced} 条` : ''} · 连线 ${r.links} 条`,
858
+ ` 库:${r.dbPath}`,
859
+ r.links > 0 ? ' 连线已写进星图 sidecar,下一轮巡检(约 12 秒)会把它们收进图里。' : '',
860
+ ].filter((x) => x !== '').join('\n'))
861
+ process.exit(0)
862
+ }
863
+
426
864
  async function cmdDoctor(args) {
427
865
  const eng = await loadEngine(args)
428
866
  const cwd = cwdOf(args)
@@ -444,8 +882,12 @@ async function cmdDoctor(args) {
444
882
  lines.push(` 子工具: ${stats.captured} 个被融合层收下`)
445
883
  lines.push(` 工具面: ${eng.tools.map((t) => t.name).join('、')}`)
446
884
  lines.push(` 注入: L0 ${eng.injection().length} 字符`)
885
+ // mac 上最常见的一种「命令行好好的、后台服务找不到 node」:GUI 会话的 PATH 里没有 Homebrew
886
+ const macPathOk = !isMac() || String(process.env.PATH ?? '').split(':').includes('/opt/homebrew/bin')
887
+ if (isMac()) lines.push(` macOS: PATH ${macPathOk ? '含 Homebrew' : '缺 /opt/homebrew/bin(GUI 启动的进程常这样)'}`)
447
888
  lines.push('')
448
889
  const problems = []
890
+ if (!macPathOk) problems.push('macOS 的 PATH 缺 /opt/homebrew/bin:命令行能用,但 GUI/launchd 起的服务可能找不到 node(serve --install-agent 会把完整 PATH 写进 plist)')
449
891
  if (!eng.ready.meow) problems.push('记忆引擎未就绪:多半是库打不开或迁移失败(跑 --verbose 看细节)')
450
892
  if (!eng.ready.nebula) problems.push('星图引擎未就绪:检索仍可用,只是没有关联扩散')
451
893
  if (!trust.trusted) problems.push('当前工作区未信任:写入会被拒绝(这是有意的防护)')
@@ -479,13 +921,74 @@ async function shareLite(args) {
479
921
  return { dataDir, client }
480
922
  }
481
923
 
924
+ /**
925
+ * `serve --install-agent` / `--uninstall-agent`:用户级后台常驻。
926
+ * 默认**不装**,只有用户显式要求才写盘;`--dry-run` 只打印服务文件与命令,零副作用。
927
+ */
928
+ async function cmdServeAgent(args) {
929
+ const { dataDir } = await shareLite(args)
930
+ const { installDaemon, uninstallDaemon } = await import('../lib/core/daemon.js')
931
+ const dryRun = args['dry-run'] === true
932
+ const port = args.port === undefined ? 0 : Number(args.port)
933
+ const common = {
934
+ dataDir,
935
+ cwd: cwdOf(args),
936
+ port,
937
+ dryRun,
938
+ execPath: process.execPath,
939
+ entryScript: fileURLToPath(import.meta.url),
940
+ }
941
+ const fmtCmds = (spec) =>
942
+ [...(spec.installCmd ?? []), ...(spec.uninstallCmd ?? [])]
943
+ .map(([cmd, argv]) => `${cmd} ${argv.join(' ')}`)
944
+ .filter((line, i, all) => all.indexOf(line) === i)
945
+
946
+ if (args['uninstall-agent'] === true) {
947
+ const res = uninstallDaemon(common)
948
+ if (args.json === true) {
949
+ out(JSON.stringify({ dryRun: res.dryRun, kind: res.kind, servicePath: res.servicePath, removed: res.removed, stopped: res.stopped }))
950
+ } else if (res.dryRun) {
951
+ out(`(演练,没动任何东西)将卸载 ${res.kind} 服务:${res.servicePath}`)
952
+ for (const line of fmtCmds(res.spec)) out(` ${line}`)
953
+ } else {
954
+ out([
955
+ `已卸载 ${res.kind} 服务:${res.servicePath}(文件已删=${res.removed},进程已停=${res.stopped})`,
956
+ '记忆库原样保留:只删服务定义与发现文件,一条记忆都不动。',
957
+ ].join('\n'))
958
+ }
959
+ process.exit(res.dryRun || res.removed || res.stopped ? 0 : 1)
960
+ }
961
+
962
+ const res = installDaemon(common)
963
+ if (args.json === true) {
964
+ out(JSON.stringify({ dryRun: res.dryRun, kind: res.kind, servicePath: res.servicePath, activated: res.activated, warning: res.warning }))
965
+ } else if (res.dryRun) {
966
+ out(`(演练,没写盘)将安装 ${res.kind} 服务:${res.servicePath}`)
967
+ out('')
968
+ out(res.spec.content.trimEnd())
969
+ out('')
970
+ for (const line of res.spec.installCmd.map(([cmd, argv]) => `${cmd} ${argv.join(' ')}`)) out(` ${line}`)
971
+ } else {
972
+ out([
973
+ `已安装 ${res.kind} 服务:${res.servicePath}(已激活=${res.activated})`,
974
+ ...(res.warning ? [` 注意:${res.warning}`] : []),
975
+ '',
976
+ ' 看状态: macro-memory share',
977
+ ' 要卸载: macro-memory serve --uninstall-agent',
978
+ ' 日志: <数据目录>/serve.log',
979
+ ].join('\n'))
980
+ }
981
+ process.exit(res.dryRun || res.activated ? 0 : 1)
982
+ }
983
+
482
984
  /**
483
985
  * `serve`:前台常驻的单写者(PLAN 第 6 节)。
484
986
  *
485
- * 三件事只有它干:唯一写连接、唯一跑 dream 的、唯一打快照的。默认前台、默认不装
486
- * 任何常驻(LaunchAgent / 计划任务得显式 `--install-agent`,这一版还没做,明写在文档里)。
987
+ * 三件事只有它干:唯一写连接、唯一跑 dream 的、唯一打快照的。默认前台;
988
+ * 要开机自启得显式 `serve --install-agent`(launchd / systemd --user / 计划任务)。
487
989
  */
488
990
  async function cmdServe(args) {
991
+ if (args['install-agent'] === true || args['uninstall-agent'] === true) return cmdServeAgent(args)
489
992
  const { startServe } = await import('../lib/core/serve.js')
490
993
  const port = args.port === undefined ? 0 : Number(args.port)
491
994
  if (!Number.isInteger(port) || port < 0 || port > 65535) {
@@ -659,6 +1162,16 @@ async function cmdUi(args) {
659
1162
  ].join('\n'),
660
1163
  )
661
1164
  }
1165
+ if (args.open === true && args.json !== true) {
1166
+ const { spawn } = await import('node:child_process')
1167
+ const spec = browserOpenSpec(ui.url)
1168
+ try {
1169
+ spawn(spec.command, spec.args, { detached: true, stdio: 'ignore' }).unref()
1170
+ out(' 已交给系统默认浏览器(--open)。')
1171
+ } catch (err) {
1172
+ out(` 打不开浏览器(${String(err?.message ?? err)}):请手动复制上面那条地址。`)
1173
+ }
1174
+ }
662
1175
  const bye = async (sig) => {
663
1176
  try {
664
1177
  await ui.close(sig)
@@ -721,6 +1234,12 @@ async function main() {
721
1234
  return cmdUi(args)
722
1235
  case 'doctor':
723
1236
  return cmdDoctor(args)
1237
+ case 'snapshot':
1238
+ return cmdSnapshot(args)
1239
+ case 'export':
1240
+ return cmdExport(args)
1241
+ case 'import':
1242
+ return cmdImport(args)
724
1243
  case 'stats':
725
1244
  return cmdStats(args)
726
1245
  default: