sage-mem 2.33.3 → 3.0.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,372 @@
1
+ /**
2
+ * sync 层 —— **上行线路**(纯编码 / 解码 + 远端脚本原文,3.0.0)。
3
+ *
4
+ * 本文件不碰磁盘、不起进程:给进去 `Buffer`,还回来 `Buffer`。真正的 ssh 在 `push.js`。
5
+ *
6
+ * ## 为什么是「长度前缀」而不是 tar
7
+ *
8
+ * 拉取(`content.js`)已经被慢链路逼成了这个形状:经 Tailscale 到一台自建主机
9
+ * 单次握手 5–20 秒,每个文件一条命令在第 3 次往返就卡到超时。上行对称处理 ——
10
+ * **一次 ssh 灌完全部正文**。
11
+ *
12
+ * tar 看着更省事,但它表达不了这一版真正要的三件事:逐条 sha256 校验、
13
+ * **排他创建**(撞名即冲突,不许覆盖)、以及覆盖前先备份。所以协议自己定,
14
+ * 但只定到「够表达这三件事」为止:
15
+ *
16
+ * ```
17
+ * STAGE <n>\n
18
+ * <len>\t<action>\t<name>\t<sha>\t<expect>\n ← 头①(行尾 LF)
19
+ * <raw bytes of file 1> ← 恰好 len 字节
20
+ * <len>\t<action>\t<name>\t<sha>\t<expect>\n ← 头②
21
+ * <raw bytes of file 2>
22
+ * ... ← 头与正文**交替**
23
+ * COMMIT\n
24
+ * ```
25
+ *
26
+ * ⚠️ 设计稿(`docs/3.0.0-push-plan.md` §3.1)画的是「n 条头在前、正文全在后」。
27
+ * 实现改成**交替**,因为那才是这一个脚本能流式处理的样子:远端读一条头就立刻把紧随的
28
+ * 正文写进临时文件,`sh` 里不需要保存 n 条头的数组(POSIX sh 没有数组,想存就得拼字符串,
29
+ * 那是所有引号事故的来源)。语义完全一样,只是帧序更省事;两侧已按交替实现,
30
+ * 文档也同步改了。改动这一帧序时**编码器与脚本必须一起改**,中间没有版本协商。
31
+ *
32
+ * `sha` 是**这次要传的正文**的 sha256(由本文件的编码器自己算,不由调用方提供 ——
33
+ * 「传的是什么」与「声明的是什么」不许有两个来源)。
34
+ * `expect` 是**远端当前那份**的 sha256(`overwrite` 用;`upload` 写 `-`)。
35
+ *
36
+ * 头字段一律用 **tab** 分隔、顺序固定、不允许缺项:远端脚本用 `read -r` 拆字段,
37
+ * 少一个字段就得多一层猜测,而猜测在写别人库的时候是奢侈品。
38
+ *
39
+ * ## 为什么文件名不进 shell
40
+ *
41
+ * 远端脚本**不把文件名拼进命令**:它们只出现在头里、被读进变量、然后以 `"$name"`
42
+ * 的形式用在双引号内。文件名里带 `$`、反引号、单引号、空格都伤不到它。
43
+ * 唯一放不进去的是 **tab**(协议分隔符)与换行 —— 编码器直接拒。
44
+ *
45
+ * ## 怎么把脚本送到远端(`sh -c`,**不是** `sh -s`)
46
+ *
47
+ * ⚠️ 这一节是一次真机推翻的产物,别再改回去。原本的设计是 `ssh <host> sh -s`,
48
+ * 打算让「脚本走 stdin、正文也走 stdin」,命令行走的只有三个字符。
49
+ * **做不到**:`sh -s` 的 stdin 归**脚本解析器**所有 —— 它一次 `read()` 把整块
50
+ * (脚本 + 紧随其后的载荷)读进自己的缓冲区,脚本里的 `IFS= read -r` 再读 fd 0 时
51
+ * 已经是 EOF 或者半截残渣。dash 与 bash 一样,`sh -s < 文件`(可 seek)也一样。
52
+ * 2026-12-05 在真机上七条用例全部停在 `FATAL bad_header`,根因就这一条。
53
+ *
54
+ * 现在:**脚本原文走命令行**(`sh -c '<脚本>'`),**正文仍然走 stdin**。
55
+ * 分界线是「谁写的、有多大」:脚本是我们自己的代码、3 KB 出头、远不到 `ARG_MAX`;
56
+ * 正文是记忆内容、可能任意字节、动辄几 MB。把小的固定件放进 argv,
57
+ * 把大的外部输入留在 stdin —— 这条线划对了,两端都稳。
58
+ */
59
+ import { sha256Of } from './content.js'
60
+ import { assertRemotePath } from './gate.js'
61
+ import { isSafeSyncName } from './policy.js'
62
+
63
+ /** 头里允许的动作(与 `policy.js` 的 `PUSH_ACTIONS` 同集合,但这里是**线格式**的一份,少一个都不用)。 */
64
+ export const UPLOAD_ACTIONS = ['upload', 'overwrite']
65
+
66
+ /** 远端脚本会打印的结果行前缀。解析与生成必须同步改。 */
67
+ export const UPLOAD_LINES = ['OK', 'CONFLICT', 'STALE', 'FAIL', 'FATAL', 'DONE', 'DONE_PARTIAL']
68
+
69
+ /**
70
+ * 一个条目在**线上**的形状(编码器的输入)。
71
+ *
72
+ * `action` 与 `expect` 都来自分类结果,编码器不重新判断 —— 判断在 `policy.js`,
73
+ * 编码器只负责把它写成字节。
74
+ *
75
+ * @typedef {object} UploadItem
76
+ * @property {string} name — 单段 `.md` 基名
77
+ * @property {'upload'|'overwrite'} action
78
+ * @property {Buffer} content
79
+ * @property {string} [expect] — 远端当前 sha256(`overwrite` 必填)
80
+ */
81
+
82
+ /**
83
+ * 校验一个要进协议的名字。
84
+ *
85
+ * `isSafeSyncName` 已经拒了 `/` `\` NUL `..` 与非 `.md`,这里再补一条**协议专属**的:
86
+ * tab 是字段分隔符,一个名字里的 tab 会让远端把后半截读成 `sha`。
87
+ * 这条约束属于线格式,不属于「什么算记忆条目」,所以放在这里而不是 `policy.js`。
88
+ *
89
+ * @param {string} name
90
+ */
91
+ export function assertUploadName(name) {
92
+ const n = String(name ?? '')
93
+ if (!isSafeSyncName(n)) throw new Error('文件名不安全(非单段 .md),拒绝上传')
94
+ if (n.includes('\t') || /[\r\n]/.test(n)) throw new Error('文件名含制表符或换行,无法进上行协议')
95
+ return n
96
+ }
97
+
98
+ /**
99
+ * 编码一整批上行字节(**纯函数**)。
100
+ *
101
+ * @param {object} input
102
+ * @param {UploadItem[]} input.items
103
+ * @returns {{buffer: Buffer, entries: Array<{name:string, action:string, sha:string, bytes:number}>, bytes: number}}
104
+ */
105
+ export function encodeUploadBatch({ items = [] } = {}) {
106
+ if (!Array.isArray(items)) throw new Error('items 必须是数组')
107
+ for (const item of items) {
108
+ if (!item || typeof item !== 'object') throw new Error('items 里有一项不是对象')
109
+ const name = assertUploadName(item.name)
110
+ if (!UPLOAD_ACTIONS.includes(item.action)) {
111
+ throw new Error(`动作不合法(${String(item.action)}):上行只接受 upload / overwrite —— 冲突与跳过不该走到这里`)
112
+ }
113
+ if (!Buffer.isBuffer(item.content)) throw new Error(`${
114
+ name} 的正文必须是 Buffer(字符串会按 UTF-8 再编一次,sha256 就对不上了)`)
115
+ const expect = item.action === 'overwrite' ? String(item.expect ?? '').toLowerCase() : '-'
116
+ if (item.action === 'overwrite' && !/^[0-9a-f]{64}$/.test(expect)) {
117
+ throw new Error(`${name} 是覆盖动作,但没给远端当前的 sha256(写之前必须能核对 revision)`)
118
+ }
119
+ }
120
+
121
+ const chunks = []
122
+ const entries = []
123
+ chunks.push(Buffer.from(`STAGE ${items.length}\n`, 'utf8'))
124
+ for (const item of items) {
125
+ const sha = sha256Of(item.content)
126
+ const expect = item.action === 'overwrite' ? String(item.expect).toLowerCase() : '-'
127
+ chunks.push(Buffer.from(`${item.content.length}\t${item.action}\t${item.name}\t${sha}\t${expect}\n`, 'utf8'))
128
+ chunks.push(item.content)
129
+ entries.push({ name: item.name, action: item.action, sha, bytes: item.content.length })
130
+ }
131
+ chunks.push(Buffer.from('COMMIT\n', 'utf8'))
132
+
133
+ const buffer = Buffer.concat(chunks)
134
+ return { buffer, entries, bytes: entries.reduce((n, e) => n + e.bytes, 0) }
135
+ }
136
+
137
+ /**
138
+ * 远端接收脚本的原文(**纯函数**:只做字符串替换,不碰磁盘)。
139
+ *
140
+ * 两段式,与设计稿一致:
141
+ * ① **暂存**:把每条正文写进 `<状态根>/incoming/<名字>.tmp` 并逐条核对 sha256。
142
+ * 这一段**不碰记忆目录**,而且任何一步失败都会 `exit`(EXIT trap 清掉暂存区)。
143
+ * ② **提交**:读 `.plan`(暂存时写下的 `动作 / 名字 / 期望 sha / 临时文件`),
144
+ * 逐条按动作落地:`upload` 排他创建,`overwrite` 先核对远端 revision、再备份、再覆盖。
145
+ *
146
+ * 为什么两段而不是边收边落盘:断线时「半个推送」最难解释 —— 报告还没生成,用户不知道
147
+ * 哪几个已经进去了。两段式让「断线」等于「什么都没进」(暂存区除外,它会被自动清掉)。
148
+ *
149
+ * 脚本**永远 `exit 0`**:报告走 stdout,不靠退出码。这样「有 3 个文件失败」与
150
+ * 「ssh 断了」在客户端是两件完全不同的事 —— 后者表现为 Promise reject,前者是可解析的结果。
151
+ *
152
+ * @param {object} input
153
+ * @param {string} input.remotePath — 远端记忆目录(原样,内部过 `quoteForShell`)
154
+ * @param {string} input.stateDir — 远端状态根(来自 `gate.js` 的 `remoteStateDirOf`)
155
+ * @returns {string}
156
+ */
157
+ export function buildUploadScript({ remotePath, stateDir }) {
158
+ // 路径形状的判据只有一份(`gate.js` 的 `assertRemotePath`):这里再抄一遍规则,
159
+ // 就会出现「门禁拒了但脚本还生成得出来」这种半开状态。
160
+ const mem = quoteLocal(assertRemotePath(remotePath, '远端记忆目录'), '远端记忆目录')
161
+ const state = quoteLocal(assertRemotePath(stateDir, '远端状态目录'), '远端状态目录')
162
+ // 注意:`${mem}` 里已经是「单引号字面量」或 `"$HOME"'/x'` 形式,可以直接跟 `=` 拼接。
163
+ return `MEM=${mem}
164
+ SD=${state}
165
+ INC="$SD/incoming"
166
+
167
+ die() { printf 'FATAL %s\\n' "$1"; exit 0; }
168
+
169
+ # 记忆目录不存在就别往下走:这时候 mv 会失败,而失败落在 FAIL mv 上,
170
+ # 读起来像「某一条文件没搬成」,实际是「远端根本没有这个目录」——两件事的处置完全不同。
171
+ [ -d "$MEM" ] || die no_mem_dir
172
+
173
+ mkdir -p "$INC" || die mkdir_incoming
174
+ # 上一次断线留下的残骸:只清 .tmp 与 .plan,绝不碰别的
175
+ trap 'rm -f "$INC"/*.tmp "$INC"/.plan 2>/dev/null' EXIT
176
+ rm -f "$INC"/*.tmp "$INC"/.plan 2>/dev/null
177
+
178
+ # 读恰好 N 字节。GNU/BSD/busybox 的 head 都支持 -c;不支持时退回 dd(慢但正确)。
179
+ if head -c 0 </dev/null >/dev/null 2>&1; then
180
+ read_bytes() { head -c "$1"; }
181
+ else
182
+ read_bytes() { dd bs=1 count="$1" 2>/dev/null; }
183
+ fi
184
+
185
+ IFS= read -r hdr || die truncated_header
186
+ case "$hdr" in
187
+ 'STAGE '*) n=\${hdr#STAGE } ;;
188
+ *) die bad_header ;;
189
+ esac
190
+ case "$n" in ''|*[!0-9]*) die bad_count ;; esac
191
+
192
+ : > "$INC/.plan" || die plan_write
193
+
194
+ i=0
195
+ while [ "$i" -lt "$n" ]; do
196
+ IFS= read -r line || die truncated_meta
197
+ len=\${line%% *}; rest=\${line#* }
198
+ action=\${rest%% *}; rest=\${rest#* }
199
+ name=\${rest%% *}; rest=\${rest#* }
200
+ sha=\${rest%% *}; expect=\${rest#* }
201
+ case "$len" in ''|*[!0-9]*) die bad_len ;; esac
202
+ case "$action" in upload|overwrite) : ;; *) die bad_action ;; esac
203
+ case "$name" in ''|*/*|..|.) die bad_name ;; esac
204
+
205
+ tmp="$INC/$name.tmp"
206
+ read_bytes "$len" > "$tmp" || die stage_failed
207
+ got=$(sha256sum "$tmp" | cut -c1-64)
208
+ if [ "$got" != "$sha" ]; then
209
+ rm -f "$tmp"
210
+ die "sha_mismatch:$name"
211
+ fi
212
+ printf '%s\t%s\t%s\t%s\\n' "$action" "$name" "$expect" "$tmp" >> "$INC/.plan" || die plan_append
213
+ i=$((i + 1))
214
+ done
215
+
216
+ IFS= read -r endline || die truncated_commit
217
+ [ "$endline" = COMMIT ] || die no_commit
218
+
219
+ # ── 提交段 ──
220
+ TS=$(date +%Y%m%d-%H%M%S)
221
+ BK="$SD/backup/$TS"
222
+ failed=0
223
+ while IFS=' ' read -r action name expect tmp; do
224
+ target="$MEM/$name"
225
+ if [ "$action" = upload ]; then
226
+ if [ -e "$target" ]; then
227
+ printf 'CONFLICT %s\\n' "$name"
228
+ failed=1
229
+ continue
230
+ fi
231
+ if mv "$tmp" "$target"; then printf 'OK upload %s\\n' "$name"
232
+ else printf 'FAIL mv %s\\n' "$name"; failed=1; fi
233
+ continue
234
+ fi
235
+ # overwrite:远端必须还是清单里那个版本,否则一个字都不写
236
+ if [ ! -f "$target" ]; then printf 'STALE %s\\n' "$name"; failed=1; continue; fi
237
+ cur=$(sha256sum "$target" | cut -c1-64)
238
+ if [ "$cur" != "$expect" ]; then printf 'STALE %s\\n' "$name"; failed=1; continue; fi
239
+ mkdir -p "$BK" || { printf 'FAIL backup_dir %s\\n' "$name"; failed=1; continue; }
240
+ if ! cp -p "$target" "$BK/$name"; then printf 'FAIL backup %s\\n' "$name"; failed=1; continue; fi
241
+ if mv "$tmp" "$target"; then printf 'OK overwrite %s\\n' "$name"
242
+ else printf 'FAIL mv %s\\n' "$name"; failed=1; fi
243
+ done < "$INC/.plan"
244
+
245
+ rm -f "$INC"/.plan
246
+ # 清理放在打印结论**之前**:EXIT trap 也会兜一次,但它在 exit 之后才跑,那时结论行已经发出去了。
247
+ # 先清再报,「说了清干净」才是当时的事实(2026-12-05 真机看到过「报 DONE、incoming 还留着空目录」)。
248
+ rm -f "$INC"/*.tmp 2>/dev/null
249
+ rmdir "$INC" 2>/dev/null
250
+ if [ "$failed" -eq 0 ]; then printf 'DONE %s\\n' "$TS"; else printf 'DONE_PARTIAL %s\\n' "$TS"; fi
251
+ exit 0
252
+ `
253
+ }
254
+
255
+ /**
256
+ * 远端**实际执行的那条命令**(`push.js` 只该用它,别自己拼 `sh -s`)。
257
+ *
258
+ * 形状是 `sh -c '<脚本原文>'`:脚本走 argv,正文走 stdin。为什么这样分 —— 见文件头那一节
259
+ * (一句话:`sh -s` 的 stdin 归脚本解析器所有,正文抢不过它)。
260
+ *
261
+ * 三个实现细节,每个都对应一次真机事故:
262
+ * 1. 整个脚本包在**单引号**里,内部单引号按 POSIX 规矩转成 `'\''`。
263
+ * **换行既不转义也不删** —— 单引号里的换行就是换行,远端 shell 照样把它当成一条多行命令。
264
+ * 2. **不能复用 `remote.js` 的 `quoteForShell()`**:那是按「一个路径」设计的,见到换行直接拒。
265
+ * 3. 显式拒 NUL:`execFile` 传 NUL 会被截断成另一条命令,而「另一条命令」比报错危险得多。
266
+ *
267
+ * @param {object} input
268
+ * @param {string} input.remotePath
269
+ * @param {string} input.stateDir
270
+ * @returns {string}
271
+ */
272
+ export function buildUploadCommand({ remotePath, stateDir }) {
273
+ const script = buildUploadScript({ remotePath, stateDir })
274
+ if (script.includes('\0')) throw new Error('远端脚本里出现 NUL,拒绝执行')
275
+ return `sh -c '${script.replace(/'/g, `'\\''`)}'`
276
+ }
277
+
278
+ /**
279
+ * 给**要进远端 shell 的路径**加引号。
280
+ *
281
+ * 与 `remote.js` 的 `quoteForShell` 是同一套规则(`~` 必须留在引号外才会展开),
282
+ * 但那一份会 `trim()` 并把空值当错误消息抛;这里要的是「原样、可复现」,
283
+ * 所以复用它的两个语义而不是它的函数体 —— 差别只在报错文案的字段名。
284
+ *
285
+ * @param {string} value
286
+ * @param {string} label
287
+ * @returns {string}
288
+ */
289
+ function quoteLocal(value, label) {
290
+ const s = String(value ?? '')
291
+ if (s.trim() === '') throw new Error(`未配置${label}`)
292
+ if (/[\0\n\r]/.test(s)) throw new Error(`${label}含控制字符,拒绝执行`)
293
+ if (s === '~') return '"$HOME"'
294
+ if (s.startsWith('~/')) return `"$HOME"'${s.slice(1).replace(/'/g, `'\\''`)}'`
295
+ if (s.startsWith('~')) throw new Error(`${label}用了 \`~用户\` 形式,无法安全展开`)
296
+ return `'${s.replace(/'/g, `'\\''`)}'`
297
+ }
298
+
299
+ /**
300
+ * 解析远端脚本的输出(纯函数)。
301
+ *
302
+ * 逐行、前缀匹配。**认不出的行不静默丢掉**:计数带回去,报告里提一句 ——
303
+ * 远端多打一行少打一行,都可能意味着这一版脚本与这一版客户端不是同一个版本。
304
+ *
305
+ * @param {string} text — 脚本的 stdout
306
+ * @returns {{
307
+ * files: Map<string, {status:'uploaded'|'overwritten'|'conflict'|'stale_remote'|'failed', code?:string}>,
308
+ * fatal: {code: string, detail: string}|null,
309
+ * done: boolean,
310
+ * partial: boolean,
311
+ * stamp: string|null,
312
+ * unparsed: number,
313
+ * }}
314
+ */
315
+ export function parseUploadOutput(text) {
316
+ const files = new Map()
317
+ const out = { files, fatal: null, done: false, partial: false, stamp: null, unparsed: 0 }
318
+
319
+ for (const rawLine of String(text ?? '').split('\n')) {
320
+ const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine
321
+ if (line.trim() === '') continue
322
+
323
+ if (line.startsWith('OK upload ')) {
324
+ files.set(line.slice('OK upload '.length), { status: 'uploaded' })
325
+ continue
326
+ }
327
+ if (line.startsWith('OK overwrite ')) {
328
+ files.set(line.slice('OK overwrite '.length), { status: 'overwritten' })
329
+ continue
330
+ }
331
+ if (line.startsWith('CONFLICT ')) {
332
+ files.set(line.slice('CONFLICT '.length), { status: 'conflict' })
333
+ continue
334
+ }
335
+ if (line.startsWith('STALE ')) {
336
+ files.set(line.slice('STALE '.length), { status: 'stale_remote' })
337
+ continue
338
+ }
339
+ if (line.startsWith('FAIL ')) {
340
+ const rest = line.slice('FAIL '.length)
341
+ const cut = rest.indexOf(' ')
342
+ const code = cut < 0 ? rest : rest.slice(0, cut)
343
+ const name = cut < 0 ? '' : rest.slice(cut + 1)
344
+ if (name !== '') files.set(name, { status: 'failed', code })
345
+ else if (out.fatal === null) out.fatal = { code, detail: '' }
346
+ continue
347
+ }
348
+ if (line.startsWith('FATAL ')) {
349
+ const rest = line.slice('FATAL '.length)
350
+ const cut = rest.indexOf(':')
351
+ const code = cut < 0 ? rest : rest.slice(0, cut)
352
+ const detail = cut < 0 ? '' : rest.slice(cut + 1)
353
+ if (out.fatal === null) out.fatal = { code, detail }
354
+ continue
355
+ }
356
+ if (line.startsWith('DONE_PARTIAL ')) {
357
+ out.done = true
358
+ out.partial = true
359
+ out.stamp = line.slice('DONE_PARTIAL '.length).trim() || null
360
+ continue
361
+ }
362
+ if (line.startsWith('DONE')) {
363
+ out.done = true
364
+ const stamp = line.slice('DONE'.length).trim()
365
+ out.stamp = stamp === '' ? null : stamp
366
+ continue
367
+ }
368
+ out.unparsed += 1
369
+ }
370
+
371
+ return out
372
+ }
@@ -15,6 +15,7 @@ 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
17
  import { runSyncPull } from '../sync/pull.js'
18
+ import { runSyncPush } from '../sync/push.js'
18
19
 
19
20
  const text = (s) => [{ type: 'text', text: String(s ?? '') }]
20
21
 
@@ -244,9 +245,134 @@ export function createSyncPullTool({ readSettings, writeMemory, overrides = {} }
244
245
  }
245
246
  }
246
247
 
248
+ /**
249
+ * `memory_sync_push` —— 跨设备第 3 步:把本地动过的推出去(3.0.0)。
250
+ *
251
+ * 与 `memory_sync_pull` 对称,但多一道**写入门**:拉取写的是自己的库,推送写的是**别人机器上的目录**。
252
+ * 所以这个工具的三层判据(状态目录 / `instance.json` / 首次确认)不是可选项,
253
+ * 它们就是「为什么可以碰别人的机器」的全部回答。
254
+ *
255
+ * 为什么 `confirm` 不在设置里而是每次参数:确认是**一次决定**,不是一个配置项。
256
+ * 设成配置就会变成「当初勾过一次,此后永远放行」,而门存在的理由是「这次这台机器还是不是我的库」。
257
+ *
258
+ * @param {object} input
259
+ * @param {() => Promise<{sync: object}>} input.readSettings — 读当前生效设置
260
+ * @param {object} [input.overrides] — 测试注入:`{ memoryDir, stateRoot, deps }`
261
+ */
262
+ export function createSyncPushTool({ readSettings, overrides = {} }) {
263
+ return {
264
+ name: 'memory_sync_push',
265
+ description:
266
+ '跨设备推送(**默认只预演**):把本机记忆目录里「一侧动过、另一侧没动」的文件推到远端(ssh 主机)—— '
267
+ + '本地新增 → 远端排他新建(撞名转冲突);仅本地改 → 先核对远端版本、备份旧文件、再覆盖;'
268
+ + '两侧都动过 → **远端一个字节都不写**,两份正文留成一条冲突记录。永不删除任何文件。'
269
+ + '写之前要过三道门:远端有 sage-mem 状态目录、身份文件读得出、这台设备已确认过 —— '
270
+ + '第一次向某台设备推送(或它换了库)必须显式传 `confirm: true`。'
271
+ + '不传 `apply: true` 时只出清单、远端一个字节都不收。',
272
+ parameters: {
273
+ type: 'object',
274
+ properties: {
275
+ host: {
276
+ type: 'string',
277
+ description: 'SSH 主机别名(~/.ssh/config 里的名字)。省略则用设置里的值。',
278
+ },
279
+ remotePath: {
280
+ type: 'string',
281
+ description: '远端记忆目录的绝对路径(或 `~` 开头)。省略则用设置里的值。',
282
+ },
283
+ confirm: {
284
+ type: 'boolean',
285
+ description:
286
+ '默认 false。第一次向这台设备推送、或远端的 deviceId 与基线不符时必须传 true —— '
287
+ + '确认的是「那是我的库」。预演永远不需要它,也永远不会记下确认。',
288
+ },
289
+ apply: {
290
+ type: 'boolean',
291
+ description:
292
+ '默认 false = 只预演(不读冲突正文、不传任何字节、不动基线)。'
293
+ + 'true = 真的执行:新建远端没有的、覆盖远端没动过的、其余留两份进冲突记录。',
294
+ },
295
+ },
296
+ required: [],
297
+ additionalProperties: false,
298
+ },
299
+ async execute(args = {}) {
300
+ try {
301
+ const settings = await readSettings().catch(() => ({ sync: DEFAULT_SYNC }))
302
+ const resolved = resolveSync(settings?.sync)
303
+
304
+ const host = String(args.host ?? '').trim() || resolved.sync.host
305
+ const remotePath = String(args.remotePath ?? '').trim() || resolved.sync.remotePath
306
+
307
+ if (host === '') {
308
+ return {
309
+ ok: false,
310
+ code: 'no_host',
311
+ error: '错误:no_host — 还没配置远端主机。在「外部访问 → 跨设备」里填 SSH 别名,或这次直接传 host 参数。',
312
+ }
313
+ }
314
+ if (remotePath === '') {
315
+ return {
316
+ ok: false,
317
+ code: 'no_remote_path',
318
+ error: '错误:no_remote_path — 还没配置远端记忆目录。在设置里填,或这次直接传 remotePath 参数。',
319
+ }
320
+ }
321
+
322
+ const out = await runSyncPush({
323
+ memoryDir: overrides.memoryDir ?? MEMORY_DIR,
324
+ stateRoot: overrides.stateRoot ?? STATE_ROOT,
325
+ host,
326
+ remotePath,
327
+ confirm: args.confirm === true,
328
+ apply: args.apply === true,
329
+ deps: { ...(overrides.deps ?? {}) },
330
+ })
331
+
332
+ if (!out.ok) {
333
+ return {
334
+ ok: false,
335
+ code: out.code ?? 'sync_failed',
336
+ error: out.error ?? '错误:sync_failed',
337
+ gate: out.gate,
338
+ content: text(out.report ?? ''),
339
+ }
340
+ }
341
+
342
+ const note = out.applied
343
+ ? ''
344
+ : '\n> 这是预演,**远端一个字节都没收,本地一个字节都没改**。确认清单无误后,再调一次并传 `apply: true`。\n'
345
+
346
+ return {
347
+ ok: true,
348
+ applied: out.applied,
349
+ confirmed: out.confirmed,
350
+ at: out.at,
351
+ host,
352
+ remotePath,
353
+ hasBase: out.hasBase,
354
+ baseUpdated: out.baseUpdated,
355
+ gate: out.gate,
356
+ summary: out.summary,
357
+ results: countByStatus(out.results),
358
+ content: text(`${out.report}${note}`),
359
+ }
360
+ } catch (err) {
361
+ const message = String(err?.message ?? err)
362
+ return {
363
+ ok: false,
364
+ code: 'sync_failed',
365
+ error: `错误:sync_failed — ${message}`,
366
+ }
367
+ }
368
+ },
369
+ }
370
+ }
371
+
247
372
  /** 执行结果的条数摘要(工具返回值里只给数,正文清单在报告里)。 */
248
373
  function countByStatus(results = []) {
249
- const out = { imported: 0, overwritten: 0, conflict: 0, failed: 0 }
374
+ // 拉取与推送的状态集合都在这儿:一个函数两处用,省得两份「摘要」慢慢长歪。
375
+ const out = { imported: 0, uploaded: 0, overwritten: 0, conflict: 0, failed: 0 }
250
376
  for (const r of results) {
251
377
  if (out[r.status] === undefined) continue
252
378
  out[r.status] += 1
@@ -15,6 +15,10 @@ import { checkpointsResultSchema } from '../shared/checkpoints-schema.js'
15
15
  import { recallDebugResultSchema } from '../shared/recall-debug-schema.js'
16
16
  import { MD_NAME_PATTERN } from '../shared/md-name.js'
17
17
  import { MAX_FILE_BYTES, MAX_RAW_BYTES } from '../shared/limits.js'
18
+ // 3.0.0:裁决方式的三个取值**只有一个来源**(`lib/sync/resolve.js` 的 RESOLVE_CHOICES)。
19
+ // 在 schema 里重抄一份 `['local','remote','manual']` 的代价是:那边加一种裁法,这里静默把它判成坏入参
20
+ // —— 面板传得出去、宿主一律 `invalid`,症状是「按钮点了没反应」而不是报错。
21
+ import { RESOLVE_CHOICES } from '../sync/resolve.js'
18
22
 
19
23
  // 文件名:与 host 侧 safeName 同一套底线 —— 非空、无路径分隔符与 Windows 非法字符、
20
24
  // 以 .md 结尾、长度有界。(真正的目录逃逸防护仍在 host 侧 safeName。)
@@ -758,6 +762,13 @@ export const conflictItemBase = z.object({
758
762
  // 这次被标失效的是哪一方(`file` 或 `otherFile`)——`undo` 唯一可信的落点。
759
763
  'invalidatedFile': z.string().readonly(),
760
764
  'truncated': z.boolean().readonly(),
765
+ // 3.0.0:来源标记与它属于哪台远端(additive 契约;老记录读到 `''`)。
766
+ // 不加这三行,strict 校验会把它们裁掉 —— 面板就永远分不出「跨设备冲突」。
767
+ // 读取侧(`memory/conflicts.js` 的 `withOriginFields` / `summarizeConflict`)已经保证
768
+ // 这两个出口都带这三个键,空串表示「老记录」,判据由消费方按 `'manual'` 处理。
769
+ 'origin': z.string().readonly(),
770
+ 'host': z.string().readonly(),
771
+ 'remotePath': z.string().readonly(),
761
772
  })
762
773
  export const conflictItemSchema = conflictItemBase.readonly()
763
774
  export const conflictRecordSchema = conflictItemBase.extend({
@@ -815,3 +826,30 @@ export const conflictRemoveResultSchema = z.object({
815
826
  'error': z.string().readonly().optional(),
816
827
  }).readonly()
817
828
 
829
+ // ── 3.0.0:裁决一条**跨设备**冲突(conflict/applyResolution)────────────────
830
+ // 与上面六条的区别:那六条裁的是本机两条记忆的先后关系(写 frontmatter 的失效标记),
831
+ // 这一条裁的是「同一个文件在两台设备上各有一份」—— 它会真的往远端 / 本地写正文,
832
+ // 所以入参多一个 `choice`,结果里多出「写到了哪边 / 基线动没动」。
833
+ //
834
+ // `id` 的判据**照抄** conflictOptsSchema 那一份(同一组记录、同一个 id 空间),
835
+ // 不在这里另立宽度:两份判据漂移的后果是「列表里看得见、裁决时说不认识这个 id」。
836
+ export const conflictApplyArgsSchema = z.object({
837
+ 'id': conflictIdSchema,
838
+ 'choice': z.enum(RESOLVE_CHOICES),
839
+ }).readonly()
840
+ // 结果的六个「回声」字段(choice / wrote / baseUpdated / status / recordId 与 ok 本身)
841
+ // **全部必填**:失败收据也带着它们(`resolveSyncConflict` 的 echo 就是这么造的),
842
+ // 界面据 `wrote` 决定文案是「已写到远端」还是「一个字节都没动」——缺了就没法说清。
843
+ // 只有 code / error / baseError 可选:成功时不该有它们。
844
+ export const conflictApplyResultSchema = z.object({
845
+ 'ok': z.boolean().readonly(),
846
+ 'code': z.string().readonly().optional(),
847
+ 'error': z.string().readonly().optional(),
848
+ 'choice': z.string().readonly(),
849
+ 'wrote': z.enum(['remote', 'local', 'none']).readonly(),
850
+ 'baseUpdated': z.boolean().readonly(),
851
+ 'baseError': z.string().readonly().optional(),
852
+ 'status': z.string().readonly(),
853
+ 'recordId': z.string().readonly(),
854
+ }).readonly()
855
+
@@ -25,6 +25,7 @@ import {
25
25
  rollbackResultSchema, modelListSchema, autodreamOptsSchema, conflictIdSchema, conflictOptsSchema, conflictItemBase,
26
26
  conflictItemSchema, conflictRecordSchema, conflictCountsSchema, conflictWroteSchema, conflictListSchema, conflictReadResultSchema,
27
27
  conflictInvalidateResultSchema, conflictDismissResultSchema, conflictUndoResultSchema, conflictRemoveResultSchema,
28
+ conflictApplyArgsSchema, conflictApplyResultSchema,
28
29
  } from './typert/schemas.js'
29
30
  export const TYPERT = {
30
31
  package: 'sage-mem',
@@ -566,6 +567,21 @@ export const TYPERT = {
566
567
  result: { mode: 'strict', typeSymbol: 'sage-mem/types#ConflictRemoveResult', schema: conflictRemoveResultSchema, create: () => conflictRemoveResultSchema },
567
568
  sourceLocation: { "file": "lib/index.js", "line": 1, "column": 1 },
568
569
  },
570
+ {
571
+ // 3.0.0:跨设备冲突的裁决(留本地 / 留远端 / 手工合并)。入参与其余六条不同 ——
572
+ // 它多一个 `choice`,所以用自己的一份参数 schema,而不是往 ConflictOpts 里塞可选字段
573
+ // (那个 schema 是六条方法共用的,塞一个「只有一条方法认」的键会让另外六条的入参含义变模糊)。
574
+ id: 'sage-mem#conflict/applyResolution',
575
+ service: 'conflict',
576
+ namespace: 'conflict',
577
+ method: 'applyResolution',
578
+ invocation: { kind: 'direct' },
579
+ parameters: [
580
+ { name: 'opts', wire: 'opts', source: 'json', codec: { mode: 'strict', typeSymbol: 'sage-mem/types#ConflictApplyArgs', schema: conflictApplyArgsSchema, create: () => conflictApplyArgsSchema } },
581
+ ],
582
+ result: { mode: 'strict', typeSymbol: 'sage-mem/types#ConflictApplyResult', schema: conflictApplyResultSchema, create: () => conflictApplyResultSchema },
583
+ sourceLocation: { "file": "lib/index.js", "line": 1, "column": 1 },
584
+ },
569
585
  ],
570
586
  model: {
571
587
  "services": [],
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.33.3",
4
+ "version": "3.0.0",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "icon": "./icon.png",