sage-mem 2.27.1 → 2.29.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,341 @@
1
+ /**
2
+ * sync 层 —— **拉取 wiring**(2.28.0)。跨设备第 2 步:把「一侧动过」的文件搬过来。
3
+ *
4
+ * 这里只做**顺序与错误处理**,判据全在 `policy.js`:
5
+ * 先看清楚(`check.js`)→ 折成计划(`planPull`)→ 预演就到此为止 →
6
+ * 真要动手时才拉正文(`content.js`)→ 逐文件处理 → 只把成功的那些推进基线。
7
+ *
8
+ * 三处顺序是有意为之,别调换:
9
+ * 1. **预演不拉正文**。差异可能在几十个文件上,预演一个字节都不该占用带宽 ——
10
+ * 更重要的是,「预演不写盘」这条承诺不能靠「拉了但没写」来成立。
11
+ * 2. **备份先于覆盖**。备份失败就**不覆盖**:一份没有退路的覆盖,出问题时无法解释。
12
+ * 3. **冲突不推进基线**。推进了就等于「这次差异已经处理过」,下次检查再也看不见它;
13
+ * 而冲突项实际上还没被任何人裁决,主库里只有本地那一版。
14
+ *
15
+ * 没有第二套账本:动作痕迹 = `base.json`(成功了什么)+ 冲突记录(留了什么)+ 备份目录
16
+ * (覆盖前长什么样)。再加一份 `actions.jsonl` 只会让「以哪个为准」变成新问题。
17
+ */
18
+ import { mkdir, readFile } from 'node:fs/promises'
19
+ import { join } from 'node:path'
20
+ import { buildConflict, listConflicts, sameConflict, writeConflict } from '../memory/conflicts.js'
21
+ import { ensureIndexEntry } from '../memory/index-file.js'
22
+ import { writeFileAtomic } from '../memory/util.js'
23
+ import { stampCompact } from '../shared/stamp.js'
24
+ import { readBase, writeBase } from './base.js'
25
+ import { runSyncCheck } from './check.js'
26
+ import { fetchRemoteContents } from './content.js'
27
+ import { CLASS_LABEL, planPull, pullSummary, renderPullReport } from './policy.js'
28
+
29
+ /**
30
+ * 一次拉取最多处理多少个文件。
31
+ *
32
+ * 这个数不是性能上限,是**语义护栏**:本地库基本为空时,远端 130 个文件全会被判成
33
+ * 「远端新增」,一次搬 130 个等同于「整库首次搬迁」 —— 那种事该用 `scp -r` 明确做一次,
34
+ * 而不是藏在一个增量同步工具里。撞上这条说明用法不对,报错比默默搬完有用。
35
+ */
36
+ const MAX_PULL_FILES = 50
37
+
38
+ /**
39
+ * 跑一次跨设备拉取。
40
+ *
41
+ * @param {object} input
42
+ * @param {string} input.memoryDir — 记忆目录(读写)
43
+ * @param {string} input.stateRoot — 状态根(基线 / 备份 / 来件正文)
44
+ * @param {string} input.host — ssh 主机别名
45
+ * @param {string} input.remotePath — 远端记忆目录
46
+ * @param {boolean} [input.apply=false] — 默认预演;只有显式 true 才写盘
47
+ * @param {number} [input.now]
48
+ * @param {number} [input.timeoutMs] — ssh 整体超时(默认见 `remote.js`)
49
+ * @param {object} [input.deps] — 注入点(测试用)
50
+ * @returns {Promise<object>}
51
+ */
52
+ export async function runSyncPull({
53
+ memoryDir,
54
+ stateRoot,
55
+ host,
56
+ remotePath,
57
+ apply = false,
58
+ now = Date.now(),
59
+ timeoutMs,
60
+ deps = {},
61
+ }) {
62
+ const at = new Date(now).toISOString()
63
+
64
+ const fetchContents = deps.fetchContents ?? fetchRemoteContents
65
+ const writeMemory = deps.writeMemory
66
+ const writeAtomic = deps.writeFileAtomic ?? writeFileAtomic
67
+ const ensureIndex = deps.ensureIndexEntry ?? ensureIndexEntry
68
+ const buildConflictFn = deps.buildConflict ?? buildConflict
69
+ const writeConflictFn = deps.writeConflict ?? writeConflict
70
+ const listConflictsFn = deps.listConflicts ?? listConflicts
71
+ const sameConflictFn = deps.sameConflict ?? sameConflict
72
+ const readBaseFn = deps.readBase ?? readBase
73
+ const writeBaseFn = deps.writeBase ?? writeBase
74
+ // 本地读:默认真读盘(备份与冲突都要用到本地那一版正文)。
75
+ const readLocal = deps.readLocalFile ?? ((name) => readFile(join(memoryDir, name), 'utf8'))
76
+
77
+ // ── ① 看清楚(复用 2.27.0 的整条链,且**不写基线**)──
78
+ const check = await runSyncCheck({
79
+ memoryDir,
80
+ stateRoot,
81
+ host,
82
+ remotePath,
83
+ updateBase: false,
84
+ now,
85
+ timeoutMs,
86
+ deps: {
87
+ fetchRemoteManifest: deps.fetchRemoteManifest,
88
+ localManifest: deps.localManifest,
89
+ readBase: readBaseFn,
90
+ writeBase: writeBaseFn,
91
+ remoteRun: deps.remoteRun,
92
+ },
93
+ })
94
+
95
+ // ── ② 折成计划 ──
96
+ const plan = planPull(check.result)
97
+ const summary = pullSummary(plan)
98
+ const todo = plan.filter((p) => p.action !== 'skip')
99
+
100
+ const base = {
101
+ ok: true,
102
+ at,
103
+ host,
104
+ remotePath,
105
+ hasBase: check.hasBase,
106
+ applied: false,
107
+ baseUpdated: false,
108
+ plan,
109
+ summary,
110
+ results: [],
111
+ skippedRemote: check.skippedRemote,
112
+ skippedLocal: check.skippedLocal,
113
+ }
114
+
115
+ if (todo.length > MAX_PULL_FILES) {
116
+ return {
117
+ ...base,
118
+ ok: false,
119
+ code: 'too_many',
120
+ error:
121
+ `错误:too_many — 这次有 ${todo.length} 个文件可以搬,超过单次上限 ${MAX_PULL_FILES}。`
122
+ + `本地库大概是空的 —— 整库首次搬迁请用 scp 明确做一次,别走增量同步。`,
123
+ report: renderPullReport({
124
+ plan, host, remotePath, at, apply: false, hasBase: check.hasBase,
125
+ skippedRemote: check.skippedRemote, skippedLocal: check.skippedLocal,
126
+ }),
127
+ }
128
+ }
129
+
130
+ // ── ③ 预演:到此为止,一个字节都不读也不写 ──
131
+ if (!apply) {
132
+ return { ...base, report: renderPullReport({
133
+ plan, host, remotePath, at, apply: false, hasBase: check.hasBase,
134
+ skippedRemote: check.skippedRemote, skippedLocal: check.skippedLocal,
135
+ }) }
136
+ }
137
+
138
+ if (typeof writeMemory !== 'function') {
139
+ return { ...base, ok: false, code: 'unsupported', error: '错误:unsupported — 拉取需要写入通道,但这次装配没给(内部错误)' }
140
+ }
141
+ if (todo.length === 0) {
142
+ return { ...base, report: renderPullReport({
143
+ plan, host, remotePath, at, apply: true, hasBase: check.hasBase,
144
+ skippedRemote: check.skippedRemote, skippedLocal: check.skippedLocal,
145
+ }) }
146
+ }
147
+
148
+ // ── ④ 只拉要处理的那些(skip 一条命令都不发)──
149
+ const stamp = stampCompact(now)
150
+ const backupDir = join(stateRoot, 'sync', 'backup', stamp)
151
+ const incomingDir = join(stateRoot, 'sync', 'incoming', stamp)
152
+ const contents = await fetchContents({
153
+ host,
154
+ remotePath,
155
+ names: todo.map((p) => p.name),
156
+ ...(Number.isFinite(timeoutMs) ? { timeoutMs } : {}),
157
+ ...(deps.contentRun ? { run: deps.contentRun } : {}),
158
+ })
159
+
160
+ const results = []
161
+ const done = [] // 成功落进主库的:{ name, sha }
162
+
163
+ // 队列里已经挂着的 open 记录。同一条冲突每次跑都会造出一个新的时间戳 id,
164
+ // 靠 id 去重是不够的 —— 必须在建之前比对「是不是同一件事」。
165
+ const openConflicts = []
166
+ try {
167
+ const listed = await listConflictsFn({ stateRoot })
168
+ if (listed?.ok) openConflicts.push(...listed.items.filter((r) => r?.status === 'open'))
169
+ } catch {
170
+ // 读不出来就当没有:最坏后果是同一件事多一条记录,不会丢任何东西。
171
+ }
172
+
173
+ /** 记一条冲突:「两份都留下」的唯一实现。 */
174
+ async function keepBoth({ name, className, remoteText, localText, expectSha, actualSha, note }) {
175
+ const record = buildConflictFn({
176
+ kind: 'external_change',
177
+ file: name,
178
+ incoming: remoteText,
179
+ onDisk: String(localText ?? ''),
180
+ // 两个版本字段在这里的含义(与「写失败」那条路的直觉不同,写清楚免得下一个人猜):
181
+ // expectedVersion = **本地那一版**(报告那一刻的 sha)—— 对应 `onDisk`
182
+ // actualVersion = **远端那一版** —— 对应 `incoming`
183
+ expectedVersion: expectSha ?? '',
184
+ actualVersion: actualSha ?? '',
185
+ note: `跨设备同步:${CLASS_LABEL[className] ?? className}${note ? `|${note}` : ''}`,
186
+ tool: 'memory_sync_pull',
187
+ at,
188
+ })
189
+ // 队列里已经有「同一件事」就不再建第二条。判据走 `sameConflict`(同一判据只许一份实现):
190
+ // 每次运行的 `at` 不同、id 的时间戳前缀也就不同,光靠 id 去重是不够的。
191
+ const twin = openConflicts.find((r) => sameConflictFn(r, record))
192
+ if (twin) return { ok: true, id: twin.id, reused: true }
193
+
194
+ try {
195
+ await mkdir(incomingDir, { recursive: true })
196
+ await writeAtomic(join(incomingDir, name), remoteText)
197
+ } catch (err) {
198
+ // 正文存不下来就不建记录:一条指向「不存在的那份」的记录比没有记录更误导。
199
+ return { ok: false, code: 'io_error', error: `远端正文存不进 ${incomingDir}(${err?.code ?? err?.message ?? err})` }
200
+ }
201
+ const written = await writeConflictFn(record, { stateRoot })
202
+ if (!written?.ok) {
203
+ return { ok: false, code: written?.code ?? 'io_error', error: written?.error ?? '冲突记录写不进去' }
204
+ }
205
+ openConflicts.push(record)
206
+ return { ok: true, id: record.id }
207
+ }
208
+
209
+ for (const item of todo) {
210
+ const got = contents?.get?.(item.name)
211
+ if (!got || !got.ok) {
212
+ results.push({
213
+ name: item.name,
214
+ status: 'failed',
215
+ code: got?.code ?? 'io_error',
216
+ error: got?.error ?? '没有拿到远端正文',
217
+ })
218
+ continue
219
+ }
220
+ // 清单里的 sha 是「拉之前」的事实;正文是「拉之后」的事实。两者不等说明远端在动,
221
+ // 或者传输改了字节 —— 宁可不写,也不把一份没验过的内容放进主库。
222
+ if (got.sha256 !== item.remote) {
223
+ results.push({
224
+ name: item.name,
225
+ status: 'failed',
226
+ code: 'stale_remote',
227
+ error: `远端正文与清单不符(清单 ${String(item.remote).slice(0, 12)}…,实得 ${got.sha256.slice(0, 12)}…),未写入`,
228
+ })
229
+ continue
230
+ }
231
+
232
+ if (item.action === 'import') {
233
+ const res = await writeMemory(item.name, got.text, { create: true })
234
+ if (!res?.ok) {
235
+ results.push({ name: item.name, status: 'failed', code: res?.code ?? 'io_error', error: res?.error ?? '写入被拒绝' })
236
+ continue
237
+ }
238
+ results.push({ name: item.name, status: 'imported' })
239
+ done.push({ name: item.name, sha: item.remote })
240
+ // 索引失败不影响主文件已经落盘这件事(与 intake/merge 同口径)。
241
+ try {
242
+ await ensureIndex(memoryDir, item.name)
243
+ } catch {
244
+ // 索引是可选件:写不进去只意味着这一条暂时不在清单里,正文已经在了。
245
+ }
246
+ continue
247
+ }
248
+
249
+ if (item.action === 'overwrite') {
250
+ let oldText
251
+ try {
252
+ oldText = await readLocal(item.name)
253
+ } catch (err) {
254
+ results.push({ name: item.name, status: 'failed', code: 'io_error', error: `读不到本地原件(${err?.code ?? err?.message ?? err}),未覆盖` })
255
+ continue
256
+ }
257
+ try {
258
+ await mkdir(backupDir, { recursive: true })
259
+ await writeAtomic(join(backupDir, item.name), oldText)
260
+ } catch (err) {
261
+ results.push({ name: item.name, status: 'failed', code: 'io_error', error: `备份失败(${err?.code ?? err?.message ?? err}),未覆盖` })
262
+ continue
263
+ }
264
+ // `expectedRevision` 用的是**检查那一刻**的本地 sha;盘上已经变了就拒绝覆盖。
265
+ const res = await writeMemory(item.name, got.text, { expectedRevision: item.local })
266
+ if (res?.ok) {
267
+ results.push({ name: item.name, status: 'overwritten' })
268
+ done.push({ name: item.name, sha: item.remote })
269
+ continue
270
+ }
271
+ if (res?.code === 'stale_revision' || res?.code === 'already_exists') {
272
+ // 报告之后、写入之前本地被改过(或文件被删/被建):这正是「两侧都动过」,
273
+ // 于是把它降级成冲突处理 —— 两份都留,谁赢由人定。
274
+ let currentText = ''
275
+ try {
276
+ currentText = await readLocal(item.name)
277
+ } catch {
278
+ currentText = ''
279
+ }
280
+ const kept = await keepBoth({
281
+ name: item.name,
282
+ className: 'both-changed',
283
+ remoteText: got.text,
284
+ localText: currentText,
285
+ expectSha: item.local,
286
+ actualSha: item.remote,
287
+ note: '本地在报告之后又被改过,覆盖被版本守卫拒下',
288
+ })
289
+ results.push(kept.ok
290
+ ? { name: item.name, status: 'conflict', conflictId: kept.id }
291
+ : { name: item.name, status: 'failed', code: kept.code, error: kept.error })
292
+ continue
293
+ }
294
+ results.push({ name: item.name, status: 'failed', code: res?.code ?? 'io_error', error: res?.error ?? '写入被拒绝' })
295
+ continue
296
+ }
297
+
298
+ if (item.action === 'conflict') {
299
+ let localText = ''
300
+ try {
301
+ localText = await readLocal(item.name)
302
+ } catch {
303
+ // 本地没有(`local-deleted-remote-changed`):留空是**事实**,不是失败。
304
+ localText = ''
305
+ }
306
+ const kept = await keepBoth({
307
+ name: item.name,
308
+ className: item.class,
309
+ remoteText: got.text,
310
+ localText,
311
+ expectSha: item.local,
312
+ actualSha: item.remote,
313
+ })
314
+ results.push(kept.ok
315
+ ? { name: item.name, status: 'conflict', conflictId: kept.id }
316
+ : { name: item.name, status: 'failed', code: kept.code, error: kept.error })
317
+ }
318
+ }
319
+
320
+ // ── ⑤ 基线:只推进真正落进主库的那些 ──
321
+ let baseUpdated = false
322
+ if (done.length > 0) {
323
+ const stored = await readBaseFn(stateRoot)
324
+ const reusable = stored && (!stored.host || stored.host === host) && (!stored.remotePath || stored.remotePath === remotePath)
325
+ const files = new Map(reusable ? stored.files : [])
326
+ for (const d of done) files.set(d.name, d.sha)
327
+ await writeBaseFn(stateRoot, { files, host, remotePath, at })
328
+ baseUpdated = true
329
+ }
330
+
331
+ return {
332
+ ...base,
333
+ applied: true,
334
+ baseUpdated,
335
+ results,
336
+ report: renderPullReport({
337
+ plan, host, remotePath, at, apply: true, hasBase: check.hasBase, results,
338
+ skippedRemote: check.skippedRemote, skippedLocal: check.skippedLocal,
339
+ }),
340
+ }
341
+ }
@@ -13,12 +13,56 @@
13
13
  */
14
14
  import { execFile } from 'node:child_process'
15
15
 
16
- /** ssh 默认超时。跨公网也够,卡住时宁可报错也不要挂着。 */
17
- export const DEFAULT_TIMEOUT_MS = 20000
16
+ /**
17
+ * ssh 默认超时。跨公网也够,卡住时宁可报错也不要挂着。
18
+ *
19
+ * 20 → 30 秒(2.28.0,2026-12-03 真机实测):经 Tailscale 到一台自建主机的 SSH 握手
20
+ * 稳定要 5–6 秒、偶发 14 秒以上,20 秒的上限在连续调用时会真的撞上 —— 而它撞上时
21
+ * 报的是「连不上远端」,读起来像主机挂了,实际只是握手慢。30 秒仍然有界,
22
+ * 而且比「把慢当成断」更接近事实。
23
+ */
24
+ export const DEFAULT_TIMEOUT_MS = 30000
18
25
 
19
26
  /** 单次清单输出的上限。130 个文件约 10 KB,给 4 MB 是「绝不可能撞上」的量级。 */
20
27
  const MAX_BUFFER = 4 * 1024 * 1024
21
28
 
29
+ /**
30
+ * 把一个「要进远端 shell 的字符串」包成单引号字面量。
31
+ *
32
+ * 三条理由逐条对应一次真实失败:
33
+ * 1. **控制字符一律拒**:换行能把一条命令拆成两条,而远端执行的是 `cd ... && ...` 的组合;
34
+ * 2. **单引号内部转义**用 `'\''` —— POSIX shell 里单引号内不能转义,只能先闭合再拼;
35
+ * 文件名的字符集里没有排除单引号,所以这不是理论问题;
36
+ * 3. **错误里不回声原文**:路径来自设置、文件名来自远端清单,两者都可能是外部输入,
37
+ * 把原文拼进异常消息会在日志里留下它(2.25.0 的审计纪律)。
38
+ *
39
+ * @param {string} value
40
+ * @param {string} [label] — 错误文案里的字段名(默认「参数」)
41
+ * @returns {string}
42
+ */
43
+ export function quoteForShell(value, label = '参数') {
44
+ const s = String(value ?? '').trim()
45
+ if (s === '') throw new Error(`未配置${label}`)
46
+ if (/[\0\n\r]/.test(s)) throw new Error(`${label}含控制字符,拒绝执行`)
47
+ // `~` **不会**在单引号里被 shell 展开 —— 2026-12-03 真机踩到:
48
+ // `cd '~/sage-mem-sync-probe/memory'` → `没有那个文件或目录`
49
+ // 所以把开头的 `~` 换成 `$HOME`,并且它必须留在引号**外**才会被求值:
50
+ // `cd "$HOME"'/sage-mem-sync-probe/memory'`
51
+ // 其余部分照旧单引号包裹(拼接后仍是同一个词,空格与控制字符都不会漏出去)。
52
+ if (s === '~') return '"$HOME"'
53
+ if (s.startsWith('~/')) return `"$HOME"${quoteLiteral(s.slice(1))}`
54
+ if (s.startsWith('~')) {
55
+ // `~user/path` 的展开规则依赖远端账户表,猜错就是「默默读错目录」。明确拒绝。
56
+ throw new Error(`${label}用了 \`~用户\` 形式,无法安全展开,请填绝对路径或只用 \`~\``)
57
+ }
58
+ return quoteLiteral(s)
59
+ }
60
+
61
+ /** 单引号字面量(`quoteForShell` 的底半截)。 */
62
+ function quoteLiteral(s) {
63
+ return `'${s.replace(/'/g, `'\\''`)}'`
64
+ }
65
+
22
66
  /**
23
67
  * 生成在**远端**执行的命令。
24
68
  *
@@ -29,10 +73,7 @@ const MAX_BUFFER = 4 * 1024 * 1024
29
73
  * @returns {string}
30
74
  */
31
75
  export function buildRemoteCommand(remotePath) {
32
- const p = String(remotePath ?? '').trim()
33
- if (p === '') throw new Error('未配置远端记忆目录')
34
- if (/[\0\n\r]/.test(p)) throw new Error('远端记忆目录含控制字符,拒绝执行')
35
- const quoted = `'${p.replace(/'/g, `'\\''`)}'`
76
+ const quoted = quoteForShell(remotePath, '远端记忆目录')
36
77
  return `cd ${quoted} && find . -maxdepth 1 -type f -name '*.md' -exec sha256sum {} +`
37
78
  }
38
79
 
@@ -49,7 +90,7 @@ export function buildRemoteCommand(remotePath) {
49
90
  * @param {Function} [input.run] — 注入点(测试用假执行器替换真 ssh)
50
91
  * @returns {Promise<{stdout: string, stderr: string}>}
51
92
  */
52
- export async function fetchRemoteManifest({ host, remotePath, timeoutMs = DEFAULT_TIMEOUT_MS, run = defaultRun }) {
93
+ export async function fetchRemoteManifest({ host, remotePath, timeoutMs = DEFAULT_TIMEOUT_MS, run = spawnSsh }) {
53
94
  const h = String(host ?? '').trim()
54
95
  if (h === '') throw new Error('未配置远端主机(SSH 别名)')
55
96
  if (/\s|[\0\n\r]/.test(h)) throw new Error('远端主机名不合法(含空白或控制字符)')
@@ -79,10 +120,14 @@ export async function fetchRemoteManifest({ host, remotePath, timeoutMs = DEFAUL
79
120
  /**
80
121
  * 真正调 ssh。抽成独立函数是为了让测试能整条绕开(`run` 注入点)。
81
122
  *
82
- * @param {{host: string, command: string, timeoutMs: number}} input
83
- * @returns {Promise<{stdout: string, stderr: string}>}
123
+ * 2.28.0 起多一个 `encoding`:拉正文时要**原始字节**(sha256 必须按字节算,
124
+ * 先解码成字符串再编回去会在非法 UTF-8 上悄悄改写内容)。默认仍按 utf8 ——
125
+ * 清单是文本,调用方不必关心。
126
+ *
127
+ * @param {{host: string, command: string, timeoutMs: number, encoding?: string}} input
128
+ * @returns {Promise<{stdout: string|Buffer, stderr: string|Buffer}>}
84
129
  */
85
- function defaultRun({ host, command, timeoutMs }) {
130
+ export function spawnSsh({ host, command, timeoutMs, encoding = 'utf8' }) {
86
131
  return new Promise((resolve, reject) => {
87
132
  execFile(
88
133
  'ssh',
@@ -92,7 +137,7 @@ function defaultRun({ host, command, timeoutMs }) {
92
137
  host,
93
138
  command,
94
139
  ],
95
- { timeout: timeoutMs, maxBuffer: MAX_BUFFER, windowsHide: true },
140
+ { timeout: timeoutMs, maxBuffer: MAX_BUFFER, windowsHide: true, encoding },
96
141
  (err, stdout, stderr) => {
97
142
  if (err) {
98
143
  const e = new Error(err.message)
@@ -14,6 +14,7 @@ import { join } from 'node:path'
14
14
  import { MEMORY_DIR, STATE_ROOT } from '../memory/config.js'
15
15
  import { runSyncCheck } from '../sync/check.js'
16
16
  import { DEFAULT_SYNC, resolveSync } from '../sync/policy.js'
17
+ import { runSyncPull } from '../sync/pull.js'
17
18
 
18
19
  const text = (s) => [{ type: 'text', text: String(s ?? '') }]
19
20
 
@@ -125,3 +126,130 @@ function pickNumbers(out) {
125
126
  export function defaultSyncPaths() {
126
127
  return { memoryDir: MEMORY_DIR, stateRoot: join(STATE_ROOT) }
127
128
  }
129
+
130
+ /**
131
+ * `memory_sync_pull` —— 跨设备第 2 步:把远端搬过来(2.28.0)。
132
+ *
133
+ * 与 `memory_sync_check` 的分工写在名字里:check 只看,pull 会写。
134
+ * **默认仍然是看的**(`apply: false`):跑一次拿到清单,确认无误再传 `apply: true`。
135
+ * 这样「我不小心点到它」的后果最多是多一份报告。
136
+ *
137
+ * 为什么不是给 check 加一个 `apply` 参数:一个工具名字里带 `check` 却能写盘,
138
+ * 是最容易被误用的形态 —— 工具描述是模型唯一会读的契约,不该在这里埋歧义。
139
+ *
140
+ * @param {object} input
141
+ * @param {() => Promise<{sync: object}>} input.readSettings — 读当前生效设置
142
+ * @param {(name:string, content:string, opts:object) => Promise<object>} input.writeMemory — 网关写入通道
143
+ * @param {object} [input.overrides] — 测试注入:`{ memoryDir, stateRoot, deps }`
144
+ */
145
+ export function createSyncPullTool({ readSettings, writeMemory, overrides = {} }) {
146
+ return {
147
+ name: 'memory_sync_pull',
148
+ description:
149
+ '跨设备拉取(**默认只预演**):把远端(ssh 主机)记忆目录里「一侧动过、另一侧没动」的文件搬进本机主库 —— '
150
+ + '远端新增 → 新建并补索引;仅远端改 → 先备份再覆盖;两侧都动过 → **一个字节都不覆盖**,'
151
+ + '两份正文都留成一条冲突记录,等你在「冲突」页签裁决。永不删除任何文件。'
152
+ + '不传 `apply: true` 时只出清单、记忆目录一个字节都不写。'
153
+ + '主机与远端目录来自设置(外部访问 → 跨设备),也可以临时传参覆盖。',
154
+ parameters: {
155
+ type: 'object',
156
+ properties: {
157
+ host: {
158
+ type: 'string',
159
+ description: 'SSH 主机别名(~/.ssh/config 里的名字)。省略则用设置里的值。',
160
+ },
161
+ remotePath: {
162
+ type: 'string',
163
+ description: '远端记忆目录的绝对路径。省略则用设置里的值。',
164
+ },
165
+ apply: {
166
+ type: 'boolean',
167
+ description:
168
+ '默认 false = 只预演(不拉正文、不写盘、不动基线)。'
169
+ + 'true = 真的执行:搬入远端新增、覆盖本地没动过的、其余留两份进冲突记录。',
170
+ },
171
+ },
172
+ required: [],
173
+ additionalProperties: false,
174
+ },
175
+ async execute(args = {}) {
176
+ try {
177
+ const settings = await readSettings().catch(() => ({ sync: DEFAULT_SYNC }))
178
+ const resolved = resolveSync(settings?.sync)
179
+
180
+ const host = String(args.host ?? '').trim() || resolved.sync.host
181
+ const remotePath = String(args.remotePath ?? '').trim() || resolved.sync.remotePath
182
+
183
+ if (host === '') {
184
+ return {
185
+ ok: false,
186
+ code: 'no_host',
187
+ error: '错误:no_host — 还没配置远端主机。在「外部访问 → 跨设备」里填 SSH 别名,或这次直接传 host 参数。',
188
+ }
189
+ }
190
+ if (remotePath === '') {
191
+ return {
192
+ ok: false,
193
+ code: 'no_remote_path',
194
+ error: '错误:no_remote_path — 还没配置远端记忆目录。在设置里填,或这次直接传 remotePath 参数。',
195
+ }
196
+ }
197
+
198
+ const deps = { ...(overrides.deps ?? {}) }
199
+ if (typeof writeMemory === 'function') deps.writeMemory = writeMemory
200
+
201
+ const out = await runSyncPull({
202
+ memoryDir: overrides.memoryDir ?? MEMORY_DIR,
203
+ stateRoot: overrides.stateRoot ?? STATE_ROOT,
204
+ host,
205
+ remotePath,
206
+ apply: args.apply === true,
207
+ deps,
208
+ })
209
+
210
+ if (!out.ok) {
211
+ return {
212
+ ok: false,
213
+ code: out.code ?? 'sync_failed',
214
+ error: out.error ?? '错误:sync_failed',
215
+ content: text(out.report ?? ''),
216
+ }
217
+ }
218
+
219
+ const note = out.applied
220
+ ? ''
221
+ : '\n> 这是预演,**记忆目录一个字节都没改**。确认清单无误后,再调一次并传 `apply: true`。\n'
222
+
223
+ return {
224
+ ok: true,
225
+ applied: out.applied,
226
+ at: out.at,
227
+ host,
228
+ remotePath,
229
+ hasBase: out.hasBase,
230
+ baseUpdated: out.baseUpdated,
231
+ summary: out.summary,
232
+ results: countByStatus(out.results),
233
+ content: text(`${out.report}${note}`),
234
+ }
235
+ } catch (err) {
236
+ const message = String(err?.message ?? err)
237
+ return {
238
+ ok: false,
239
+ code: 'sync_failed',
240
+ error: `错误:sync_failed — ${message}`,
241
+ }
242
+ }
243
+ },
244
+ }
245
+ }
246
+
247
+ /** 执行结果的条数摘要(工具返回值里只给数,正文清单在报告里)。 */
248
+ function countByStatus(results = []) {
249
+ const out = { imported: 0, overwritten: 0, conflict: 0, failed: 0 }
250
+ for (const r of results) {
251
+ if (out[r.status] === undefined) continue
252
+ out[r.status] += 1
253
+ }
254
+ return out
255
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "sage-mem",
3
3
  "description": "Cross-session memory for DeepSeek Harness — plain markdown files, no database, no worker.",
4
- "version": "2.27.1",
4
+ "version": "2.29.0",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "icon": "./icon.png",