macro-memory 0.0.0-stage → 0.9.1

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 (200) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +386 -2
  3. package/bin/macro-memory.mjs +735 -0
  4. package/docs/CHANGELOG.md +268 -0
  5. package/docs/MAC.md +156 -0
  6. package/docs/images/_architecture.svg +70 -0
  7. package/docs/images/_memory-flow.svg +75 -0
  8. package/docs/images/_token-budget.svg +40 -0
  9. package/docs/images/architecture.png +0 -0
  10. package/docs/images/hero.png +0 -0
  11. package/docs/images/memory-flow.png +0 -0
  12. package/docs/images/src/graph.html +78 -0
  13. package/docs/images/src/hero.html +88 -0
  14. package/docs/images/src/panel.html +63 -0
  15. package/docs/images/src/pipeline.html +97 -0
  16. package/docs/images/token-budget.png +0 -0
  17. package/lib/client.js +3811 -0
  18. package/lib/core/agents-file.js +95 -0
  19. package/lib/core/client.js +313 -0
  20. package/lib/core/compat/dsh-llm.js +78 -0
  21. package/lib/core/config.js +117 -0
  22. package/lib/core/engine.js +456 -0
  23. package/lib/core/fence.js +109 -0
  24. package/lib/core/index.js +102 -0
  25. package/lib/core/migrate.js +70 -0
  26. package/lib/core/mini-host.js +324 -0
  27. package/lib/core/owner.js +347 -0
  28. package/lib/core/paths.js +95 -0
  29. package/lib/core/serve.js +378 -0
  30. package/lib/core/trust.js +173 -0
  31. package/lib/index.js +567 -0
  32. package/lib/macro/brand.js +82 -0
  33. package/lib/macro/bridge.js +158 -0
  34. package/lib/macro/chain.js +206 -0
  35. package/lib/macro/contract.js +471 -0
  36. package/lib/macro/cost.js +164 -0
  37. package/lib/macro/defs/admin.js +528 -0
  38. package/lib/macro/defs/dream.js +24 -0
  39. package/lib/macro/defs/link.js +408 -0
  40. package/lib/macro/defs/project.js +237 -0
  41. package/lib/macro/defs/read.js +160 -0
  42. package/lib/macro/defs/remember.js +411 -0
  43. package/lib/macro/defs/search.js +899 -0
  44. package/lib/macro/defs/update.js +161 -0
  45. package/lib/macro/dreamledger.js +1398 -0
  46. package/lib/macro/facade.js +135 -0
  47. package/lib/macro/fusion.js +188 -0
  48. package/lib/macro/injectledger.js +843 -0
  49. package/lib/macro/linkflow.js +391 -0
  50. package/lib/macro/links.js +448 -0
  51. package/lib/macro/neighbor.js +1083 -0
  52. package/lib/macro/panel.js +96 -0
  53. package/lib/macro/platform.js +134 -0
  54. package/lib/macro/prompt.js +139 -0
  55. package/lib/macro/provenance.js +148 -0
  56. package/lib/macro/render.js +35 -0
  57. package/lib/macro/revisions.js +253 -0
  58. package/lib/macro/shared.js +113 -0
  59. package/lib/macro/shortid.js +114 -0
  60. package/lib/macro/snapshot.js +700 -0
  61. package/lib/macro/spend.js +312 -0
  62. package/lib/macro/store.js +238 -0
  63. package/lib/macro/supersede.js +197 -0
  64. package/lib/macro/tokencost.js +90 -0
  65. package/lib/macro/tools.js +67 -0
  66. package/lib/mcp/server.js +201 -0
  67. package/lib/mcp/stdio.js +151 -0
  68. package/lib/ui/page.js +300 -0
  69. package/lib/ui/server.js +226 -0
  70. package/package.json +56 -4
  71. package/vendor/VENDOR.json +39 -0
  72. package/vendor/cosmokit/LICENSE +21 -0
  73. package/vendor/cosmokit/README.md +30 -0
  74. package/vendor/cosmokit/lib/index.js +418 -0
  75. package/vendor/cosmokit/lib/types/array.d.ts +15 -0
  76. package/vendor/cosmokit/lib/types/array.d.ts.map +1 -0
  77. package/vendor/cosmokit/lib/types/index.d.ts +13 -0
  78. package/vendor/cosmokit/lib/types/index.d.ts.map +1 -0
  79. package/vendor/cosmokit/lib/types/misc.d.ts +41 -0
  80. package/vendor/cosmokit/lib/types/misc.d.ts.map +1 -0
  81. package/vendor/cosmokit/lib/types/string.d.ts +89 -0
  82. package/vendor/cosmokit/lib/types/string.d.ts.map +1 -0
  83. package/vendor/cosmokit/lib/types/time.d.ts +19 -0
  84. package/vendor/cosmokit/lib/types/time.d.ts.map +1 -0
  85. package/vendor/cosmokit/lib/types/types.d.ts +42 -0
  86. package/vendor/cosmokit/lib/types/types.d.ts.map +1 -0
  87. package/vendor/cosmokit/lib/types/volatile.d.ts +40 -0
  88. package/vendor/cosmokit/lib/types/volatile.d.ts.map +1 -0
  89. package/vendor/cosmokit/package.json +32 -0
  90. package/vendor/cosmokit/src/array.ts +42 -0
  91. package/vendor/cosmokit/src/index.ts +12 -0
  92. package/vendor/cosmokit/src/misc.ts +78 -0
  93. package/vendor/cosmokit/src/string.ts +113 -0
  94. package/vendor/cosmokit/src/time.ts +92 -0
  95. package/vendor/cosmokit/src/types.ts +168 -0
  96. package/vendor/cosmokit/src/volatile.ts +86 -0
  97. package/vendor/dsh-memory-nebula/CONTRIBUTING.md +48 -0
  98. package/vendor/dsh-memory-nebula/LICENSE +21 -0
  99. package/vendor/dsh-memory-nebula/README.en.md +203 -0
  100. package/vendor/dsh-memory-nebula/README.md +253 -0
  101. package/vendor/dsh-memory-nebula/SECURITY.md +43 -0
  102. package/vendor/dsh-memory-nebula/SUPPORT.md +33 -0
  103. package/vendor/dsh-memory-nebula/cordis.patch.yml +4 -0
  104. package/vendor/dsh-memory-nebula/lib/client.js +105 -0
  105. package/vendor/dsh-memory-nebula/lib/host/adapters/index.js +279 -0
  106. package/vendor/dsh-memory-nebula/lib/host/adapters/ingest.js +230 -0
  107. package/vendor/dsh-memory-nebula/lib/host/adapters/meow.js +320 -0
  108. package/vendor/dsh-memory-nebula/lib/host/adapters/notes.js +305 -0
  109. package/vendor/dsh-memory-nebula/lib/host/adapters/sqlite.js +287 -0
  110. package/vendor/dsh-memory-nebula/lib/host/adapters/util.js +231 -0
  111. package/vendor/dsh-memory-nebula/lib/host/bridge.js +351 -0
  112. package/vendor/dsh-memory-nebula/lib/host/compress.js +97 -0
  113. package/vendor/dsh-memory-nebula/lib/host/demo.js +357 -0
  114. package/vendor/dsh-memory-nebula/lib/host/diagnostics.js +125 -0
  115. package/vendor/dsh-memory-nebula/lib/host/doctor.js +270 -0
  116. package/vendor/dsh-memory-nebula/lib/host/entities.js +230 -0
  117. package/vendor/dsh-memory-nebula/lib/host/graph.js +1762 -0
  118. package/vendor/dsh-memory-nebula/lib/host/graphcache.js +290 -0
  119. package/vendor/dsh-memory-nebula/lib/host/http.js +993 -0
  120. package/vendor/dsh-memory-nebula/lib/host/injectcfg.js +95 -0
  121. package/vendor/dsh-memory-nebula/lib/host/ledger.js +175 -0
  122. package/vendor/dsh-memory-nebula/lib/host/live.js +204 -0
  123. package/vendor/dsh-memory-nebula/lib/host/nebula.js +2105 -0
  124. package/vendor/dsh-memory-nebula/lib/host/page.js +75 -0
  125. package/vendor/dsh-memory-nebula/lib/host/path.js +83 -0
  126. package/vendor/dsh-memory-nebula/lib/host/recall.js +526 -0
  127. package/vendor/dsh-memory-nebula/lib/host/share.js +633 -0
  128. package/vendor/dsh-memory-nebula/lib/host/sources.js +266 -0
  129. package/vendor/dsh-memory-nebula/lib/host/store.js +333 -0
  130. package/vendor/dsh-memory-nebula/lib/host/text.js +410 -0
  131. package/vendor/dsh-memory-nebula/lib/host/transcripts.js +396 -0
  132. package/vendor/dsh-memory-nebula/lib/index.js +782 -0
  133. package/vendor/dsh-memory-nebula/lib/standalone.mjs +315 -0
  134. package/vendor/dsh-memory-nebula/lib/web/api.js +426 -0
  135. package/vendor/dsh-memory-nebula/lib/web/app.js +4172 -0
  136. package/vendor/dsh-memory-nebula/lib/web/i18n.js +580 -0
  137. package/vendor/dsh-memory-nebula/lib/web/index.html +174 -0
  138. package/vendor/dsh-memory-nebula/lib/web/nav.js +132 -0
  139. package/vendor/dsh-memory-nebula/lib/web/render.js +1890 -0
  140. package/vendor/dsh-memory-nebula/lib/web/space3d.js +1883 -0
  141. package/vendor/dsh-memory-nebula/lib/web/style.css +1402 -0
  142. package/vendor/dsh-memory-nebula/locale/en.json +7 -0
  143. package/vendor/dsh-memory-nebula/locale/zh.json +7 -0
  144. package/vendor/dsh-memory-nebula/market/assets/icon-180.png +0 -0
  145. package/vendor/dsh-memory-nebula/market/assets/icon.svg +40 -0
  146. package/vendor/dsh-memory-nebula/market/index.json +101 -0
  147. package/vendor/dsh-memory-nebula/package.json +87 -0
  148. package/vendor/dsh-memory-nebula/sidecar.ps1 +119 -0
  149. package/vendor/meow-memory/LICENSE +21 -0
  150. package/vendor/meow-memory/README.en.md +192 -0
  151. package/vendor/meow-memory/README.md +174 -0
  152. package/vendor/meow-memory/README.pt-br.md +180 -0
  153. package/vendor/meow-memory/cordis.patch.yml +7 -0
  154. package/vendor/meow-memory/lib/client.js +3354 -0
  155. package/vendor/meow-memory/lib/client.js.map +7 -0
  156. package/vendor/meow-memory/lib/index.js +13500 -0
  157. package/vendor/meow-memory/lib/index.js.map +7 -0
  158. package/vendor/meow-memory/lib/prompts/README.md +65 -0
  159. package/vendor/meow-memory/lib/prompts/en/dream-atomic.md +36 -0
  160. package/vendor/meow-memory/lib/prompts/en/dream-header.md +9 -0
  161. package/vendor/meow-memory/lib/prompts/en/dream-project-summary.md +12 -0
  162. package/vendor/meow-memory/lib/prompts/en/dream-topic.md +27 -0
  163. package/vendor/meow-memory/lib/prompts/en/external-memory-notice.md +8 -0
  164. package/vendor/meow-memory/lib/prompts/en/first-create-notice.md +8 -0
  165. package/vendor/meow-memory/lib/prompts/en/labels.md +104 -0
  166. package/vendor/meow-memory/lib/prompts/en/reflect.md +31 -0
  167. package/vendor/meow-memory/lib/prompts/en/system-guide.md +121 -0
  168. package/vendor/meow-memory/lib/prompts/en/tools.md +83 -0
  169. package/vendor/meow-memory/lib/prompts/en/welcome-guide.md +12 -0
  170. package/vendor/meow-memory/lib/prompts/pt-br/dream-atomic.md +36 -0
  171. package/vendor/meow-memory/lib/prompts/pt-br/dream-header.md +9 -0
  172. package/vendor/meow-memory/lib/prompts/pt-br/dream-project-summary.md +12 -0
  173. package/vendor/meow-memory/lib/prompts/pt-br/dream-topic.md +27 -0
  174. package/vendor/meow-memory/lib/prompts/pt-br/external-memory-notice.md +8 -0
  175. package/vendor/meow-memory/lib/prompts/pt-br/first-create-notice.md +8 -0
  176. package/vendor/meow-memory/lib/prompts/pt-br/labels.md +104 -0
  177. package/vendor/meow-memory/lib/prompts/pt-br/reflect.md +31 -0
  178. package/vendor/meow-memory/lib/prompts/pt-br/system-guide.md +121 -0
  179. package/vendor/meow-memory/lib/prompts/pt-br/tools.md +83 -0
  180. package/vendor/meow-memory/lib/prompts/pt-br/welcome-guide.md +12 -0
  181. package/vendor/meow-memory/lib/prompts/zh/dream-atomic.md +36 -0
  182. package/vendor/meow-memory/lib/prompts/zh/dream-header.md +9 -0
  183. package/vendor/meow-memory/lib/prompts/zh/dream-project-summary.md +19 -0
  184. package/vendor/meow-memory/lib/prompts/zh/dream-topic.md +27 -0
  185. package/vendor/meow-memory/lib/prompts/zh/external-memory-notice.md +8 -0
  186. package/vendor/meow-memory/lib/prompts/zh/first-create-notice.md +8 -0
  187. package/vendor/meow-memory/lib/prompts/zh/labels.md +104 -0
  188. package/vendor/meow-memory/lib/prompts/zh/reflect.md +30 -0
  189. package/vendor/meow-memory/lib/prompts/zh/system-guide.md +119 -0
  190. package/vendor/meow-memory/lib/prompts/zh/tools.md +83 -0
  191. package/vendor/meow-memory/lib/prompts/zh/welcome-guide.md +12 -0
  192. package/vendor/meow-memory/package.json +64 -0
  193. package/vendor/schemastery/LICENSE +21 -0
  194. package/vendor/schemastery/README.md +393 -0
  195. package/vendor/schemastery/lib/index.cjs +635 -0
  196. package/vendor/schemastery/lib/index.mjs +637 -0
  197. package/vendor/schemastery/lib/types/index.d.ts +211 -0
  198. package/vendor/schemastery/lib/types/index.d.ts.map +1 -0
  199. package/vendor/schemastery/package.json +39 -0
  200. package/vendor/schemastery/src/index.ts +962 -0
@@ -0,0 +1,700 @@
1
+ /**
2
+ * [macro-fusion 0.6.68 / 0.6.69] 记忆库快照:把「库被写坏一次 = 记忆全灭」变成「退一份回去」。
3
+ * 0.6.69 补的是另一半——**退之前先看清楚要退掉什么**(`compareWithLive` 只读做差,见文件下半段)。
4
+ *
5
+ * 病(2026-11-25 的真事,见 docs/INTERNAL.md 9.267):16:38 一个开发脚本把 4,096 字节的空壳
6
+ * fixture 库盖到了活库上,2,613 条记忆当场只剩一个空 schema。引擎自己有一个
7
+ * `backupMemoryDb()`(dream 收尾时 `VACUUM INTO` 成 `memory.db.bak`),但它的配置默认
8
+ * `backup: { enabled: false }`——事故前**一个字节的备份都没有**,最后靠翻 174MB 会话转写与
9
+ * 半年前的分析快照,才把 2,202 条抠回来。
10
+ *
11
+ * 三条处方,各自只解决一件事:
12
+ * ① **不复用那一个 `.bak`**。单份备份在「连续几次写坏」面前等于没有:第二份坏库一来,
13
+ * 唯一的好备份就被盖掉了。这里按时间戳一份一份留(默认 7 份),谁坏都还有别的。
14
+ * ② **取快照只走 `VACUUM INTO`**,不做文件复制。库正被写时直接复制出来是撕裂的;
15
+ * 而撕裂的快照比没有快照更坏——它会让人以为「退得回去」。
16
+ * ③ **便宜到可以每轮问一次**:先 stat(`memory.db` 与 `-wal` 的 mtime、最新快照的 mtime),
17
+ * 库没变就一个字节都不写、连库都不打开;真变了才 VACUUM,且默认一小时最多一次。
18
+ *
19
+ * 边界(改这个文件之前先读):
20
+ * - 快照目录在 `$DSH_HOME/macro-memory/snapshots/<工作区尾部>`,**不放进 `.dsh-meow`**:
21
+ * 那里是记忆引擎的地盘,我们的缓存不该跟库混在一起(也躲开同步器/宿主清理)。
22
+ * - 这里**只写快照,不做复原**。复原要停进程、要删 `-wal`/`-shm`,属于危险动作,
23
+ * 必须由人看着做(`tools/restore-live-db.mjs`,Windows 另有 `.ps1` 版),面板只给现成命令。
24
+ * - 任何失败都回在返回值里,不抛——快照是保险,不是主流程。
25
+ */
26
+ import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readSync, renameSync, rmSync, statSync } from 'node:fs'
27
+ import { basename, join } from 'node:path'
28
+ import * as Meow from '../../vendor/meow-memory/lib/index.js'
29
+ import { isWindows } from './platform.js'
30
+ import { macroHome } from './store.js'
31
+
32
+ /**
33
+ * `node:sqlite` 的取法(0.7.0 · mac 适配):**不用顶层静态 import**。
34
+ *
35
+ * 静态 import 一个不存在的内置模块,会让整个插件在**加载阶段**就抛——连 8 个工具都注册不上,
36
+ * 用户看到的是一句 `Cannot find module 'node:sqlite'`,而不是「快照这一层不可用」。
37
+ * 这个模块是 Node 22.5 才加的(22.x 带实验标记、24 起稳定),而 DSH 桌面端各平台不是同一个
38
+ * 构建:mac 版的 Electron/Node 与 Windows 版不保证一致(本机 Windows 宿主自带
39
+ * v24.21.0,`node:sqlite` 在)。所以这里改成动态 import + 失败即降级:
40
+ * 记忆读写、检索、注入一行都不受影响,只有「库快照」这一层明确说清「这台机器取不到」。
41
+ *
42
+ * 注意范围:引擎(`vendor/meow-memory/lib/index.js:12`)自己仍静态 import `node:sqlite` ——
43
+ * 插件本体要求宿主 Node ≥ 22.5 这条底线由它决定,本文件只负责「快照层」不在这个前提之外
44
+ * 再制造一个新的崩溃点。`tools/probe-platform.mjs` 会同时钉住这两件事。
45
+ */
46
+ let DatabaseSyncCtor = null
47
+ let sqliteLoadError = ''
48
+ try {
49
+ const mod = await import('node:sqlite')
50
+ const ctor = mod?.DatabaseSync ?? mod?.default?.DatabaseSync ?? null
51
+ if (typeof ctor === 'function') DatabaseSyncCtor = ctor
52
+ else sqliteLoadError = 'node:sqlite 里没有 DatabaseSync 导出'
53
+ } catch (err) {
54
+ sqliteLoadError = String(err?.message ?? err)
55
+ }
56
+
57
+ /** 这台机器的 Node 有没有 `node:sqlite`(自检与面板都问这一句,不各自 try/catch)。 */
58
+ export function sqliteAvailable() {
59
+ return typeof DatabaseSyncCtor === 'function'
60
+ }
61
+
62
+ /** 不可用的原因(可用时是空串)——回执要能说清「为什么这次没有快照」。 */
63
+ export function sqliteReason() {
64
+ return sqliteAvailable() ? '' : sqliteLoadError || '这一版 Node 没有内置 node:sqlite'
65
+ }
66
+
67
+ /** 默认留几份。7 份 ≈ 一周(一天一次到几次),够退到「出事之前」。 */
68
+ export const SNAPSHOT_KEEP = 7
69
+ /** 两次快照的最小间隔:库每轮都在写,不设间隔等于每轮 VACUUM 一次。 */
70
+ export const SNAPSHOT_GAP_MS = 60 * 60 * 1000
71
+ /** 快照文件名里的时间戳格式,也是排序依据(字典序=时间序)。 */
72
+ const NAME_RE = /^memory-(\d{4})(\d\d)(\d\d)-(\d\d)(\d\d)(\d\d)\.db$/
73
+
74
+ const pad = (n) => String(n).padStart(2, '0')
75
+
76
+ /** 快照文件名里的本地时间戳(和人对表,不用 UTC)。 */
77
+ export function stampOf(ms) {
78
+ const d = new Date(ms)
79
+ return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
80
+ }
81
+
82
+ /** 时间戳 → 毫秒(解析不出来回 0,排序时自然沉底)。 */
83
+ function msOf(name) {
84
+ const m = NAME_RE.exec(name)
85
+ if (m === null) return 0
86
+ return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6])).getTime()
87
+ }
88
+
89
+ /**
90
+ * 快照目录:一个工作区一个子目录,名字取工作区路径尾部 96 字符(绝对路径含 `:` `\` `/`,
91
+ * 直接当目录名在 Windows 上写不进去;同一台机器上尾部才是区分度所在,与 neighbor-suspect 同口径)。
92
+ */
93
+ export function snapshotDir(workspace) {
94
+ const raw = String(workspace ?? '').trim()
95
+ const safe = raw.replace(/[^A-Za-z0-9_.-]+/g, '_').slice(-96)
96
+ return join(macroHome(), 'snapshots', safe === '' ? 'unknown' : safe)
97
+ }
98
+
99
+ /**
100
+ * 盘上的快照清单,最新在前。
101
+ * 目录不存在 → 空数组;单个文件 stat 失败 → 跳过(一行坏文件不该让清单读不出来)。
102
+ */
103
+ export function listSnapshots(workspace) {
104
+ const dir = snapshotDir(workspace)
105
+ let names = []
106
+ try {
107
+ names = readdirSync(dir)
108
+ } catch {
109
+ return []
110
+ }
111
+ const out = []
112
+ for (const name of names) {
113
+ if (!NAME_RE.test(name)) continue
114
+ const file = join(dir, name)
115
+ try {
116
+ const st = statSync(file)
117
+ out.push({ name, file, bytes: st.size, at: st.mtimeMs, stamp: msOf(name) })
118
+ } catch {
119
+ /* 一个读不到的文件不参与清单 */
120
+ }
121
+ }
122
+ out.sort((a, b) => b.stamp - a.stamp)
123
+ return out
124
+ }
125
+
126
+ /**
127
+ * 只留最近 `keep` 份,多出来的删掉(先删最老的)。
128
+ * 返回删掉的份数;任何一步失败都只落在返回值里。
129
+ */
130
+ export function pruneSnapshots(workspace, keep = SNAPSHOT_KEEP) {
131
+ const list = listSnapshots(workspace)
132
+ if (keep <= 0 || list.length <= keep) return 0
133
+ let removed = 0
134
+ for (const item of list.slice(keep)) {
135
+ try {
136
+ rmSync(item.file, { force: true })
137
+ removed += 1
138
+ } catch {
139
+ /* 删不掉就留着,下次再删 */
140
+ }
141
+ }
142
+ return removed
143
+ }
144
+
145
+ /** 库文件本身的时间戳(`memory.db` 与它的 `-wal` 取最大——有 WAL 时新内容在 WAL 里)。 */
146
+ function dataMtimeOf(dbPath) {
147
+ let ms = 0
148
+ for (const p of [dbPath, `${dbPath}-wal`]) {
149
+ try {
150
+ ms = Math.max(ms, statSync(p).mtimeMs)
151
+ } catch {
152
+ /* 没有这个文件 */
153
+ }
154
+ }
155
+ return ms
156
+ }
157
+
158
+ /**
159
+ * 取一份快照(按需:库没变、或距上一份不到 `gapMs`,就什么都不做)。
160
+ *
161
+ * @returns {{status:string, file?:string, bytes?:number, removed?:number, skipped?:string, error?:string}}
162
+ * status: `taken` 真存了 / `fresh` 库没变或刚存过 / `no-ws` 拿不到工作区 /
163
+ * `no-db` 这个工作区还没有库 / `error` 存失败(`error` 里是原话)
164
+ */
165
+ export function takeSnapshot({
166
+ workspace = '',
167
+ dir = '.dsh-meow',
168
+ keep = SNAPSHOT_KEEP,
169
+ gapMs = SNAPSHOT_GAP_MS,
170
+ now = Date.now(),
171
+ force = false,
172
+ meow = Meow,
173
+ } = {}) {
174
+ const ws = String(workspace ?? '').trim()
175
+ if (ws === '') return { status: 'no-ws' }
176
+ let dbPath
177
+ try {
178
+ dbPath = meow.memoryDbPath(ws, dir)
179
+ } catch (err) {
180
+ return { status: 'error', error: String(err?.message ?? err) }
181
+ }
182
+ if (!existsSync(dbPath)) return { status: 'no-db' }
183
+ const list = listSnapshots(ws)
184
+ const last = list[0]
185
+ if (!force && last !== undefined) {
186
+ // 两条闸:①库自上一份之后没再写过 → 存了也是同一份;②刚存过 → 别每轮都存。
187
+ if (last.at >= dataMtimeOf(dbPath)) return { status: 'fresh', file: last.file, skipped: 'unchanged' }
188
+ if (now - last.at < gapMs) return { status: 'fresh', file: last.file, skipped: 'gap' }
189
+ }
190
+ const outDir = snapshotDir(ws)
191
+ let file = join(outDir, `memory-${stampOf(now)}.db`)
192
+ if (existsSync(file)) {
193
+ // 同一秒里存两次:文件名只到秒,硬存就会盖掉前一份。非强制时认已有的那份(不另起名);
194
+ // `force` 是「现在就要一份新的」,那就把时间戳往后挪到下一个空位——最多挪 60 秒,
195
+ // 挪满还撞就当这一秒已经存过,绝不覆盖已有快照。
196
+ if (!force) return { status: 'fresh', file, skipped: 'same-second' }
197
+ let step = 0
198
+ while (step < 60 && existsSync(file)) {
199
+ step += 1
200
+ file = join(outDir, `memory-${stampOf(now + step * 1000)}.db`)
201
+ }
202
+ if (existsSync(file)) return { status: 'fresh', file, skipped: 'same-second' }
203
+ }
204
+ const tmp = `${file}.tmp`
205
+ try {
206
+ mkdirSync(outDir, { recursive: true })
207
+ // `VACUUM INTO` 要求目标文件不存在;上次中途失败可能留下 .tmp,先清掉。
208
+ if (existsSync(tmp)) rmSync(tmp, { force: true })
209
+ meow.getDb(ws, dir).vacuumInto(tmp)
210
+ renameSync(tmp, file)
211
+ } catch (err) {
212
+ try {
213
+ rmSync(tmp, { force: true })
214
+ } catch {
215
+ /* 清理失败不影响结论 */
216
+ }
217
+ return { status: 'error', error: String(err?.message ?? err) }
218
+ }
219
+ const removed = pruneSnapshots(ws, keep)
220
+ let bytes = 0
221
+ try {
222
+ bytes = statSync(file).size
223
+ } catch {
224
+ /* 刚写完就 stat 失败:字节数留 0,不影响「存下来了」这个结论 */
225
+ }
226
+ return { status: 'taken', file, bytes, removed }
227
+ }
228
+
229
+ /** 字节数说成人话(面板用;不进判定)。 */
230
+ export function humanBytes(n) {
231
+ const v = Number(n)
232
+ if (!Number.isFinite(v) || v <= 0) return '0 B'
233
+ if (v < 1024) return `${v} B`
234
+ if (v < 1024 * 1024) return `${(v / 1024).toFixed(1)} KB`
235
+ return `${(v / (1024 * 1024)).toFixed(2)} MB`
236
+ }
237
+
238
+ /**
239
+ * 复原要人看着做:面板只给现成命令,不给「一键覆盖」。
240
+ *
241
+ * [0.7.0 · mac 适配] 命令按平台给:Windows 上是 `copy` / `del`,mac 与 Linux 上是
242
+ * `cp` / `rm -f`。原先这里只写 `copy` / `del`,mac 用户照抄会得到
243
+ * `copy: command not found`——「给了错命令」比「没给命令」更坏:他以为自己照着做了。
244
+ * 脚本那一行也统一指向跨平台的 `tools/restore-live-db.mjs`(`.ps1` 只作 Windows 备选)。
245
+ */
246
+ export function restoreHint(workspace, dir = '.dsh-meow', file = '') {
247
+ let dbPath = ''
248
+ try {
249
+ dbPath = Meow.memoryDbPath(workspace, dir)
250
+ } catch {
251
+ dbPath = join(String(workspace ?? ''), dir, 'memory.db')
252
+ }
253
+ const src = file === '' ? '<快照文件>' : file
254
+ const win = isWindows()
255
+ const copyLine = win ? `copy "${src}" "${dbPath}"` : `cp "${src}" "${dbPath}"`
256
+ const rmLine = win ? `del "${dbPath}-wal" "${dbPath}-shm"` : `rm -f "${dbPath}-wal" "${dbPath}-shm"`
257
+ return [
258
+ '复原(先退出 DSH,别让进程握着库):',
259
+ ` 1) 备份现状:把 ${dbPath}(连同 -wal / -shm)复制到别处`,
260
+ ` 2) 拷回快照:${copyLine}`,
261
+ ` 3) 删掉旧日志:${rmLine}(留着会被回放,覆盖回来的库又变坏)`,
262
+ '仓库里有一份做了同样三件事的脚本:node tools/restore-live-db.mjs --source "<快照文件>"(先加 --dry-run 看一眼)。',
263
+ ].join('\n')
264
+ }
265
+
266
+ /**
267
+ * [macro-fusion 0.6.69] 退之前先看清楚要退掉什么。
268
+ *
269
+ * 病:0.6.68 让「库坏了」有了退路,但**退哪一份、退掉多少、会不会把今天写的东西一起扔掉**,
270
+ * 全要人去猜。9.268 的边界④就是这么写的:「真丢了只能退到上一份,退完之后的增量照样没了」——
271
+ * 事故现场最需要的恰恰是这一句读数:快照 2,197 条、现库 2,202 条,退回去丢掉 5 条(哪 5 条)。
272
+ *
273
+ * 处方:**只读**地把两份库各数一遍,按 id 做差。三条边界:
274
+ * - 快照用独立的 `DatabaseSync(file, { readOnly: true })` 打开:不碰引擎的缓存连接、不上写锁,
275
+ * 它是一份静止的库文件,没有任何理由让它参与 WAL 那一套;
276
+ * - 现库走引擎已经开着的那个连接(`meow.getDb`),不另开一个写句柄去抢锁;开之前先
277
+ * `existsSync` 判一下——引擎的 `getDb` 会顺手建库,面板不该有副作用;
278
+ * - 差集只报「多了/少了多少条、按层分布、前几条标题」,**不做内容级 diff**:
279
+ * 面板是拿来做「退还是不退」这决定的,不是拿来看逐字改动。
280
+ */
281
+ /** 库里的七张表(层)。顺序与引擎 `LEVELS` 一致:面板按这个顺序念,读起来跟体检/星图一个口味。 */
282
+ export const SNAPSHOT_LEVELS = ['soul', 'user', 'project', 'fact', 'lesson', 'topic', 'rules']
283
+
284
+ /** 只读打开一个库文件(快照用)。失败只回 `{status:'error'}`,不抛。 */
285
+ export function openReadOnly(file) {
286
+ if (!existsSync(file)) return { status: 'no-file' }
287
+ // 先认文件头:SQLite 库以 `SQLite format 3\0` 开头。少了这一步,坏文件(空壳、被别的
288
+ // 东西写过的 4 KB)也能「打开成功」——每张表都查不出来、`readShape` 就回 0 条,
289
+ // 面板于是念成「快照 0 条、之后新写 2,202 条」。**坏快照读成空库,比读不出来更坏。**
290
+ try {
291
+ const fd = openSync(file, 'r')
292
+ try {
293
+ const head = Buffer.alloc(16)
294
+ const got = readSync(fd, head, 0, 16, 0)
295
+ if (got < 16 || head.subarray(0, 16).toString('latin1') !== 'SQLite format 3\u0000') {
296
+ return { status: 'error', error: '不是 SQLite 库(文件头不对)' }
297
+ }
298
+ } finally {
299
+ closeSync(fd)
300
+ }
301
+ } catch (err) {
302
+ return { status: 'error', error: String(err?.message ?? err) }
303
+ }
304
+ // [0.7.0 · mac 适配] 取不到 `node:sqlite` 时**不抛**:快照是保险,不是主流程。
305
+ // 走到这里说明文件在、头也对,缺的是运行时能力——必须说清是哪一种,别让面板念成「库坏了」。
306
+ if (!sqliteAvailable()) {
307
+ return { status: 'error', error: `这台机器的 Node 取不到 node:sqlite(${sqliteReason()}),快照层这次不工作` }
308
+ }
309
+ try {
310
+ const db = new DatabaseSyncCtor(file, { readOnly: true })
311
+ // 头对了也可能半张表:真查一次 sqlite_master,查不动就是坏库。
312
+ db.prepare('SELECT COUNT(*) AS n FROM sqlite_master').get()
313
+ return { status: 'ok', db }
314
+ } catch (err) {
315
+ return { status: 'error', error: String(err?.message ?? err) }
316
+ }
317
+ }
318
+
319
+ /**
320
+ * 一个库的形状:每条 id 属于哪一层、有没有标题、总共几条、最近一次写入。
321
+ * 表不在(老库、半张 schema、坏库)就跳过那张表——**坏一张不该让整份读数作废**。
322
+ */
323
+ export function readShape(handle) {
324
+ const byLevel = {}
325
+ const ids = new Map()
326
+ const titles = new Map()
327
+ let total = 0
328
+ let newest = 0
329
+ for (const table of SNAPSHOT_LEVELS) {
330
+ let rows = []
331
+ try {
332
+ rows = handle.prepare(`SELECT id, title, content, updated_at FROM ${table}`).all()
333
+ } catch {
334
+ continue
335
+ }
336
+ byLevel[table] = rows.length
337
+ for (const row of rows) {
338
+ const id = String(row.id ?? '')
339
+ if (id === '') continue
340
+ ids.set(id, table)
341
+ const title = typeof row.title === 'string' && row.title.trim() !== '' ? row.title.trim() : String(row.content ?? '').trim()
342
+ titles.set(id, title)
343
+ total += 1
344
+ const at = Number(row.updated_at)
345
+ if (Number.isFinite(at) && at > newest) newest = at
346
+ }
347
+ }
348
+ return { total, byLevel, ids, titles, newest }
349
+ }
350
+
351
+ /** 两份形状做差:现库多出来的(快照之后写的)、快照有现库没有的(退回去会带回来的)。 */
352
+ export function shapeDiff(live, snap) {
353
+ const added = []
354
+ const removed = []
355
+ for (const [id, level] of live.ids) if (!snap.ids.has(id)) added.push({ id, level, title: live.titles.get(id) ?? '' })
356
+ for (const [id, level] of snap.ids) if (!live.ids.has(id)) removed.push({ id, level, title: snap.titles.get(id) ?? '' })
357
+ const tally = (list) => {
358
+ const out = {}
359
+ for (const item of list) out[item.level] = (out[item.level] ?? 0) + 1
360
+ return out
361
+ }
362
+ return { added, removed, addedByLevel: tally(added), removedByLevel: tally(removed) }
363
+ }
364
+
365
+ /**
366
+ * 挑一份「真能打开」的快照:默认最新在前找第一份读得动的;给了 `file` 就用它。
367
+ * 为什么要挑:坏掉的那一份常常正好是最新的(写到一半断电、盘满、被别的程序写过)——
368
+ * 面板如果把复原命令指向它,等于让人往坑里跳。
369
+ * @returns {{item?:object, list:object[], skipped:object[], explicit:boolean}}
370
+ */
371
+ export function pickSnapshot(workspace, { file = '' } = {}) {
372
+ const list = listSnapshots(workspace)
373
+ if (file !== '') {
374
+ const found = list.find((x) => x.file === file)
375
+ return { item: found ?? { file, at: 0, stamp: 0, bytes: 0, name: basename(file) }, list, skipped: [], explicit: true }
376
+ }
377
+ const skipped = []
378
+ for (const item of list) {
379
+ const probe = openReadOnly(item.file)
380
+ if (probe.status === 'ok') {
381
+ try {
382
+ probe.db.close()
383
+ } catch {
384
+ /* 关不掉不影响判断 */
385
+ }
386
+ return { item, list, skipped, explicit: false }
387
+ }
388
+ skipped.push({ name: item.name, file: item.file, error: probe.error ?? probe.status })
389
+ }
390
+ return { item: undefined, list, skipped, explicit: false }
391
+ }
392
+
393
+ /**
394
+ * 拿最新一份「读得动」的快照(或指定那一份)与现库对比。
395
+ *
396
+ * @returns {{status:string, file?:string, live?:object, snapshot?:object, added?:object, removed?:object, skipped?:object[], error?:string}}
397
+ * `ok` / `no-ws` / `no-snapshot`(一份都没有)/ `no-usable-snapshot`(有文件但全读不动)/
398
+ * `no-db` / `snapshot-error`(指定那一份读不动)/ `snapshot-empty`(能读但一条都没有)/ `error`
399
+ */
400
+ export function compareWithLive({ workspace = '', dir = '.dsh-meow', file = '', sample = 3, meow = Meow } = {}) {
401
+ const ws = String(workspace ?? '').trim()
402
+ if (ws === '') return { status: 'no-ws' }
403
+ const picked = pickSnapshot(ws, { file })
404
+ if (picked.item === undefined) {
405
+ return picked.list.length === 0
406
+ ? { status: 'no-snapshot' }
407
+ : { status: 'no-usable-snapshot', skipped: picked.skipped }
408
+ }
409
+ const target = picked.item
410
+ const skipped = picked.skipped
411
+ let dbPath = ''
412
+ try {
413
+ dbPath = meow.memoryDbPath(ws, dir)
414
+ } catch {
415
+ dbPath = ''
416
+ }
417
+ if (dbPath === '' || !existsSync(dbPath)) return { status: 'no-db', file: target.file, skipped }
418
+ const snap = openReadOnly(target.file)
419
+ if (snap.status !== 'ok') return { status: 'snapshot-error', file: target.file, error: snap.error ?? snap.status, skipped }
420
+ try {
421
+ const snapShape = readShape(snap.db)
422
+ let liveHandle
423
+ try {
424
+ liveHandle = meow.getDb(ws, dir)
425
+ } catch (err) {
426
+ return { status: 'error', file: target.file, error: String(err?.message ?? err) }
427
+ }
428
+ const liveShape = readShape(liveHandle.db)
429
+ // 9.267 的现场就是这种库:文件是好的 SQLite(4,096 字节,`sqlite_master` 查得动),
430
+ // 但七张表一条都没有。**退它等于把现库清空**,所以不能报成「之后新写 2,202 条」,
431
+ // 得单独说一句「这一份是空的」。
432
+ if (snapShape.total === 0 && liveShape.total > 0) {
433
+ return {
434
+ status: 'snapshot-empty',
435
+ file: target.file,
436
+ at: target.at ?? 0,
437
+ skipped,
438
+ live: { total: liveShape.total, byLevel: liveShape.byLevel, newest: liveShape.newest },
439
+ snapshot: { total: 0, byLevel: snapShape.byLevel, newest: 0 },
440
+ }
441
+ }
442
+ const diff = shapeDiff(liveShape, snapShape)
443
+ const limit = Math.max(0, Math.floor(Number(sample) || 0))
444
+ const brief = (list2, byLevel) => ({
445
+ total: list2.length,
446
+ byLevel,
447
+ sample: list2.slice(0, limit).map((x) => ({ id: x.id, level: x.level, title: x.title })),
448
+ })
449
+ return {
450
+ status: 'ok',
451
+ file: target.file,
452
+ at: target.at ?? 0,
453
+ skipped,
454
+ live: { total: liveShape.total, byLevel: liveShape.byLevel, newest: liveShape.newest },
455
+ snapshot: { total: snapShape.total, byLevel: snapShape.byLevel, newest: snapShape.newest },
456
+ added: brief(diff.added, diff.addedByLevel),
457
+ removed: brief(diff.removed, diff.removedByLevel),
458
+ }
459
+ } catch (err) {
460
+ return { status: 'error', file: target.file, error: String(err?.message ?? err) }
461
+ } finally {
462
+ try {
463
+ snap.db.close()
464
+ } catch {
465
+ /* 关不掉不影响读数 */
466
+ }
467
+ }
468
+ }
469
+
470
+ /** 「按层分布」说成人话:`fact 3 · lesson 2`(顺序固定,只列有条的层)。 */
471
+ export function levelTally(byLevel = {}) {
472
+ const parts = []
473
+ for (const level of SNAPSHOT_LEVELS) {
474
+ const n = Number(byLevel?.[level]) || 0
475
+ if (n > 0) parts.push(`${level} ${n}`)
476
+ }
477
+ return parts.join(' · ')
478
+ }
479
+
480
+ /** 标题截短(面板一行):去掉换行、超长咬断。 */
481
+ function shortTitle(text) {
482
+ const one = String(text ?? '').replace(/\s+/g, ' ').trim()
483
+ return one.length <= 24 ? one : `${one.slice(0, 24)}…`
484
+ }
485
+
486
+ /**
487
+ * 对比读数 → 面板那几行。`ok` 时一定给「快照多少条 → 现库多少条 + 新写几条」,
488
+ * 有样本就再给一行标题;`removed > 0` 单独说一句「退回去会带回来」。
489
+ */
490
+ export function compareLines(cmp, { stamp = '' } = {}) {
491
+ const when = stamp === '' ? '最新快照' : `最新快照(${stamp})`
492
+ if (cmp === undefined || cmp === null) return [` · 与${when}对比:这次没读到(不是「一模一样」)`]
493
+ if (cmp.status === 'no-snapshot') return []
494
+ if (cmp.status === 'snapshot-empty') {
495
+ return [
496
+ ` · 与${when}比:这一份里一条记忆都没有(空 schema / 坏库)——**退它等于把现库 ${cmp.live?.total ?? 0} 条全清掉**`,
497
+ ]
498
+ }
499
+ if (cmp.status !== 'ok') {
500
+ const why =
501
+ cmp.status === 'no-db'
502
+ ? '这个工作区还没有库'
503
+ : cmp.status === 'no-ws'
504
+ ? '拿不到工作区'
505
+ : cmp.status === 'no-usable-snapshot'
506
+ ? `盘上有 ${cmp.skipped?.length ?? 0} 份快照,但一份都打不开——这时候没有退路,先别动库`
507
+ : `读不出来:${cmp.error ?? cmp.status}`
508
+ return [` · 与${when}对比没做成:${why}`]
509
+ }
510
+ const before = cmp.snapshot.total
511
+ const after = cmp.live.total
512
+ const added = cmp.added?.total ?? 0
513
+ const removed = cmp.removed?.total ?? 0
514
+ const lines = []
515
+ if (added === 0 && removed === 0) {
516
+ lines.push(` · 与${when}一致:${after} 条,之后没有新写、也没有丢条`)
517
+ } else {
518
+ const arrow = `快照 ${before} 条 → 现库 ${after} 条`
519
+ lines.push(` · 与${when}比:${arrow}${added > 0 ? `,之后新写 ${added} 条(${levelTally(cmp.added.byLevel)})` : ''}`)
520
+ if (added > 0 && Array.isArray(cmp.added.sample) && cmp.added.sample.length > 0) {
521
+ lines.push(` 新写的例如:${cmp.added.sample.map((x) => shortTitle(x.title)).filter(Boolean).join(' / ')}`)
522
+ }
523
+ if (removed > 0) {
524
+ lines.push(
525
+ ` 快照里有 ${removed} 条现库没有了(${levelTally(cmp.removed.byLevel)})——退到这一份会把它们带回来`,
526
+ )
527
+ }
528
+ }
529
+ return lines
530
+ }
531
+
532
+ /** 面板口径说明(`scope` 那一段)。 */
533
+ export function snapshotScope({ list = [], keep = SNAPSHOT_KEEP, dbBytes = 0 } = {}) {
534
+ if (list.length === 0) {
535
+ return dbBytes > 0 ? '还没有快照(库在,但没到存的条件,或刚装上)' : '还没有快照'
536
+ }
537
+ const total = list.reduce((n, x) => n + x.bytes, 0)
538
+ return `${list.length} 份 · 共 ${humanBytes(total)} · 最多留 ${keep} 份`
539
+ }
540
+
541
+ /** 人对表用的时间:`2026-11-25 17:50`。 */
542
+ export function humanStamp(ms) {
543
+ const v = Number(ms)
544
+ if (!Number.isFinite(v) || v <= 0) return '—'
545
+ const d = new Date(v)
546
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
547
+ }
548
+
549
+ /** 「多久以前」,只做量级(面板用;不进判定)。 */
550
+ function agoText(ms, now) {
551
+ const d = Math.max(0, now - ms)
552
+ if (d < 60 * 1000) return '刚刚'
553
+ if (d < 60 * 60 * 1000) return `${Math.floor(d / 60000)} 分钟前`
554
+ if (d < 24 * 60 * 60 * 1000) return `${Math.floor(d / 3600000)} 小时前`
555
+ return `${Math.floor(d / 86400000)} 天前`
556
+ }
557
+
558
+ /**
559
+ * 面板正文:库现状 + 快照清单 + 复原入口。数字全部念盘上的东西,面板不自己算「应该有几份」。
560
+ * 只读:绝不在这里顺手存一份(存快照的唯一出口是 `takeSnapshot`,面板要存就显式调)。
561
+ */
562
+ export function readSnapshotPanel({
563
+ workspace = '',
564
+ dir = '.dsh-meow',
565
+ keep = SNAPSHOT_KEEP,
566
+ limit = 7,
567
+ now = Date.now(),
568
+ compare = true,
569
+ } = {}) {
570
+ const ws = String(workspace ?? '').trim()
571
+ if (ws === '') {
572
+ return { body: '拿不到工作区——快照是按工作区存的,这次一份都列不出来(不是「没有快照」)。', scope: '' }
573
+ }
574
+ let dbPath = ''
575
+ try {
576
+ dbPath = Meow.memoryDbPath(ws, dir)
577
+ } catch {
578
+ dbPath = ''
579
+ }
580
+ let dbBytes = 0
581
+ let dbAt = 0
582
+ if (dbPath !== '') {
583
+ try {
584
+ const st = statSync(dbPath)
585
+ dbBytes = st.size
586
+ dbAt = st.mtimeMs
587
+ } catch {
588
+ /* 库不在或读不到:下面按「没有库」说 */
589
+ }
590
+ }
591
+ const list = listSnapshots(ws)
592
+ const lines = []
593
+ lines.push(`库:${dbPath === '' ? '(路径取不到)' : dbPath}`)
594
+ if (dbBytes > 0) {
595
+ const verdict =
596
+ list.length === 0
597
+ ? '· 库里还没有任何快照'
598
+ : list[0].at >= dbAt
599
+ ? '· 快照不比库旧'
600
+ : `· 库比最新快照还新(差 ${Math.max(1, Math.round((dbAt - list[0].at) / 60000))} 分钟)`
601
+ lines.push(` ${humanBytes(dbBytes)} · 最后写入 ${humanStamp(dbAt)} ${verdict}`)
602
+ } else {
603
+ lines.push(' 这个工作区还没有记忆库——没有可快照的东西。')
604
+ }
605
+ // [macro-fusion 0.6.69] 「退之前先看清楚要退掉什么」:只读地与最新那份比一次。
606
+ // 只在库和快照都在的时候比;任何失败都只落成一行说明,不影响上面那些读数。
607
+ let cmp
608
+ if (compare && list.length > 0 && dbBytes > 0) {
609
+ try {
610
+ cmp = compareWithLive({ workspace: ws, dir })
611
+ } catch (err) {
612
+ cmp = { status: 'error', error: String(err instanceof Error ? err.message : err) }
613
+ }
614
+ const usable = typeof cmp?.file === 'string' && cmp.file !== '' ? cmp.file : list[0].file
615
+ const at = list.find((x) => x.file === usable)?.stamp ?? list[0].stamp
616
+ for (const line of compareLines(cmp, { stamp: humanStamp(at) })) lines.push(line)
617
+ if (Array.isArray(cmp?.skipped) && cmp.skipped.length > 0) {
618
+ lines.push(
619
+ ` 另有 ${cmp.skipped.length} 份读不出来,已跳过(退的时候别选它们):${cmp.skipped.map((x) => x.name).join(' / ')}`,
620
+ )
621
+ }
622
+ }
623
+ lines.push('')
624
+ if (list.length === 0) {
625
+ lines.push('快照:还没有。库第一次变动后(下一轮注入时)会自己存第一份;也可以现在手动存:memory_admin(action="snapshot", limit=…)。')
626
+ } else {
627
+ lines.push(`快照(${Math.min(limit, list.length)}/${list.length} 份,新→旧):`)
628
+ for (const item of list.slice(0, Math.max(0, limit))) {
629
+ const bad = Array.isArray(cmp?.skipped) && cmp.skipped.some((x) => x.file === item.file)
630
+ lines.push(
631
+ ` ${humanStamp(item.stamp)} · ${humanBytes(item.bytes)} · ${agoText(item.stamp, now)} · ${item.name}${bad ? '(读不出来)' : ''}`,
632
+ )
633
+ }
634
+ if (list.length > limit) lines.push(` …更早的 ${list.length - limit} 份没列(加快 limit)`)
635
+ lines.push('')
636
+ // 复原命令指向「最新一份读得动的」:坏掉的那份常常就是最新的,指错等于让人往坑里跳。
637
+ const usable = typeof cmp?.file === 'string' && cmp.file !== '' ? cmp.file : ''
638
+ if (usable === '' && cmp !== undefined && cmp.status === 'no-usable-snapshot') {
639
+ lines.push('复原:盘上的快照一份都打不开,现在没有能退的东西——先别动库,找一份外部备份。')
640
+ } else {
641
+ lines.push(restoreHint(ws, dir, usable === '' ? list[0].file : usable))
642
+ }
643
+ lines.push('')
644
+ lines.push(
645
+ `什么时候会自动存下一份:库里再有写入、且距最新这份满 ${Math.round(SNAPSHOT_GAP_MS / 60000)} 分钟(最多留 ${keep} 份,多了删最老的)。`,
646
+ )
647
+ }
648
+ let scope = snapshotScope({ list, keep, dbBytes })
649
+ scope += ` · 间隔 ${Math.round(SNAPSHOT_GAP_MS / 60000)} 分钟`
650
+ return { body: lines.join('\n'), scope }
651
+ }
652
+
653
+ /**
654
+ * 每轮问一次「库变了没有」,变了才存。
655
+ *
656
+ * 为什么挂在 `agent/pre-step` 而不是写入路径:记忆库不是只有 memory_* 工具在写(dream、合并、
657
+ * 邻域读时补连线都在写),在工具出口挂会漏掉一半;挂在每轮的入口,问的是同一件事
658
+ * 「这一轮开始时库是什么样」,而那一下只是两次 stat——库没变就一个字节都不写。
659
+ *
660
+ * 为什么 `next()` 之后才动手:快照要读整库,别挡在这一轮的第一个 token 前面;
661
+ * 但也不等 `await` 完再存(那会把快照拖到下一轮),`next()` 返回后同步做完即可。
662
+ * 失败只记一行日志,绝不影响这一轮——保险不该变成单点。
663
+ */
664
+ export function createSnapshotGuard({ ctx, meowDir, logger, keep = SNAPSHOT_KEEP, gapMs = SNAPSHOT_GAP_MS } = {}) {
665
+ const quiet = (msg) => {
666
+ try {
667
+ logger?.(msg)
668
+ } catch {
669
+ /* 日志也不能反咬 */
670
+ }
671
+ }
672
+ let busy = false
673
+ const attempt = (payload) => {
674
+ if (busy) return
675
+ const ws = typeof payload?.agent?.session?.header?.cwd === 'string' ? payload.agent.session.header.cwd : ''
676
+ if (ws === '') return
677
+ busy = true
678
+ try {
679
+ const raw = typeof meowDir === 'function' ? meowDir() : meowDir
680
+ const dir = typeof raw === 'string' && raw.length > 0 ? raw : '.dsh-meow'
681
+ const r = takeSnapshot({ workspace: ws, dir, keep, gapMs })
682
+ if (r.status === 'taken') {
683
+ quiet(`[macro-memory] 库快照已存:${r.file}(${humanBytes(r.bytes)}${r.removed > 0 ? `,清掉 ${r.removed} 份旧的` : ''})`)
684
+ } else if (r.status === 'error') {
685
+ quiet(`[macro-memory] 库快照没做成(不影响这一轮):${r.error}`)
686
+ }
687
+ } catch (err) {
688
+ quiet(`[macro-memory] 库快照出错(不影响这一轮):${err instanceof Error ? err.message : String(err)}`)
689
+ } finally {
690
+ busy = false
691
+ }
692
+ }
693
+ if (typeof ctx?.on !== 'function') return { attempt, dispose: () => {} }
694
+ const dispose = ctx.on('agent/pre-step', async (payload, next) => {
695
+ const decision = await next()
696
+ attempt(payload)
697
+ return decision
698
+ })
699
+ return { attempt, dispose: typeof dispose === 'function' ? dispose : () => {} }
700
+ }