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.
@@ -11,7 +11,7 @@
11
11
  * 安全:`remotePath` 来自设置(人填的),但仍然是**要进远端 shell 的字符串** ——
12
12
  * 一律单引号包裹并转义内部单引号,拒绝换行与控制字符。主机名同样不拼进命令。
13
13
  */
14
- import { execFile } from 'node:child_process'
14
+ import { execFile, spawn as spawnProcess } from 'node:child_process'
15
15
 
16
16
  /**
17
17
  * ssh 默认超时。跨公网也够,卡住时宁可报错也不要挂着。
@@ -117,6 +117,25 @@ export async function fetchRemoteManifest({ host, remotePath, timeoutMs = DEFAUL
117
117
  return { stdout, stderr }
118
118
  }
119
119
 
120
+ /**
121
+ * ssh 的**公共前缀**(不含远端命令本身)。
122
+ *
123
+ * 抽出来不是为了少打几个字,而是 3.0.0 的推送要走**另一条通道**:`execFile` 只能读、
124
+ * 写不了 stdin,推送必须换成 `child_process.spawn`(`spawnSshInput`)。两条通道的
125
+ * `BatchMode` / `ConnectTimeout` / 主机名必须**逐字节相同** —— 否则会出现「拉取连得上、
126
+ * 推送连不上」这种只在一条腿上发作的问题,而它的现场最难复现。
127
+ *
128
+ * @param {string} host — `~/.ssh/config` 里的主机别名
129
+ * @returns {string[]} 前缀(调用方自行追加 `command`)
130
+ */
131
+ export function sshArgv(host) {
132
+ return [
133
+ '-o', 'BatchMode=yes', // 绝不弹交互式密码提示:拿不到密钥就直接失败
134
+ '-o', 'ConnectTimeout=10',
135
+ host,
136
+ ]
137
+ }
138
+
120
139
  /**
121
140
  * 真正调 ssh。抽成独立函数是为了让测试能整条绕开(`run` 注入点)。
122
141
  *
@@ -124,19 +143,23 @@ export async function fetchRemoteManifest({ host, remotePath, timeoutMs = DEFAUL
124
143
  * 先解码成字符串再编回去会在非法 UTF-8 上悄悄改写内容)。默认仍按 utf8 ——
125
144
  * 清单是文本,调用方不必关心。
126
145
  *
127
- * @param {{host: string, command: string, timeoutMs: number, encoding?: string}} input
146
+ * ⚠️ **必须把 stdin 关掉**(2026-12-05 真机实测,别再删):
147
+ * `execFile` 默认给子进程开一条 stdin 管道并且**从不关闭**。Windows 上的 `ssh.exe`
148
+ * 在某些时序下会等 stdin,命令早就跑完了它也不退出,一路挂到调用方的 `timeout`
149
+ * 把它 SIGTERM 掉 —— 于是每 20 次里有 3 次白等满 30 秒,报出来的却是
150
+ * 「连不上远端」,读起来像主机挂了。同一批命令关掉 stdin 之后 20/20 全通、
151
+ * 中位耗时没变(≈0.4 s)。探门 / 清单 / 取正文三条路都走这个函数,
152
+ * 一次推送要 2–4 条 ssh —— 不修的话单次推送有三到五成概率白等。
153
+ *
154
+ * @param {{host: string, command: string, timeoutMs: number, encoding?: string, exec?: Function}} input
155
+ * @param {Function} [input.exec] — 注入点(测试用假 `execFile` 验「stdin 真的被关了」)
128
156
  * @returns {Promise<{stdout: string|Buffer, stderr: string|Buffer}>}
129
157
  */
130
- export function spawnSsh({ host, command, timeoutMs, encoding = 'utf8' }) {
158
+ export function spawnSsh({ host, command, timeoutMs, encoding = 'utf8', exec = execFile }) {
131
159
  return new Promise((resolve, reject) => {
132
- execFile(
160
+ const child = exec(
133
161
  'ssh',
134
- [
135
- '-o', 'BatchMode=yes', // 绝不弹交互式密码提示:拿不到密钥就直接失败
136
- '-o', 'ConnectTimeout=10',
137
- host,
138
- command,
139
- ],
162
+ [...sshArgv(host), command],
140
163
  { timeout: timeoutMs, maxBuffer: MAX_BUFFER, windowsHide: true, encoding },
141
164
  (err, stdout, stderr) => {
142
165
  if (err) {
@@ -150,5 +173,111 @@ export function spawnSsh({ host, command, timeoutMs, encoding = 'utf8' }) {
150
173
  resolve({ stdout, stderr })
151
174
  },
152
175
  )
176
+ // 见上面那段:这条管道不关,ssh 就会在某些时序下等一个永远不会来的 EOF。
177
+ // 命令本身不需要 stdin(我们从不往里写),直接给一个 EOF 是最便宜的解法。
178
+ try {
179
+ child.stdin?.end()
180
+ } catch {
181
+ // 子进程已经退出、管道已销毁:与我们无关,结论仍由回调决定。
182
+ }
183
+ })
184
+ }
185
+
186
+ /**
187
+ * 往 ssh 的 stdin 写**原始字节**,把它的 stdout / stderr 收回来(都是字符串)。
188
+ *
189
+ * 为什么需要它:3.0.0 的推送要把 N 个文件的正文**一次性**灌给远端的 `sh -s` 脚本 ——
190
+ * 一次握手传完整批,而不是每个文件起一条 ssh。`spawnSsh` 走的是 `execFile`,
191
+ * 它只能读 stdout、给不了 stdin,所以这条路必须换成 `child_process.spawn`。
192
+ *
193
+ * 三个坑,各对应一种真实失败:
194
+ *
195
+ * 1. **EPIPE 必须吞掉**。远端脚本通常先做门禁(版本、目录、锁)再读正文;门禁一不过就
196
+ * `exit 1` 收工。我们这边还在 `stdin.write`,管道另一头已经关了 —— 没人接的 `'error'`
197
+ * 事件会**直接把宿主进程崩掉**,而真相只是「远端拒绝了这次推送」。所以 stdin 的 error
198
+ * 一律丢弃,结论只看退出码与 stderr。
199
+ * 2. **超时不能指望 ssh 自己**。`ConnectTimeout=10` 管的是 TCP 握手,管不了「连上了,
200
+ * 但远端卡在读锁 / 等另一台机器」。到点必须自己 `kill`,并带出 `timedOut: true`,
201
+ * 让上层分得清「网断了」和「远端还活着但没动静」。
202
+ * 3. **stdout 只用来读脚本的结果行**,所以按 utf8 收字符串并封顶 `MAX_BUFFER`:
203
+ * 远端脚本一旦写错成 `cat 正文`,这道闸门会在炸内存之前先掐掉它(`code: 'too_big'`)。
204
+ *
205
+ * 正文本身走 stdin,因此这里**不需要** `encoding: 'buffer'`;也不要设 `shell: true` ——
206
+ * 那样 `command` 会被本机 shell 再解析一遍,引号规则全变。
207
+ *
208
+ * @param {object} input
209
+ * @param {string} input.host — `~/.ssh/config` 里的主机别名
210
+ * @param {string} input.command — 远端子命令(如 `sh -s`)
211
+ * @param {Buffer|string} input.input — 写进 stdin 的内容;字符串按 utf8 编
212
+ * @param {number} [input.timeoutMs]
213
+ * @param {Function} [input.spawn] — 注入点(测试用 `node -e` 顶替真 ssh)
214
+ * @returns {Promise<{stdout: string, stderr: string}>}
215
+ */
216
+ export function spawnSshInput({ host, command, input, timeoutMs = DEFAULT_TIMEOUT_MS, spawn = spawnProcess }) {
217
+ return new Promise((resolve, reject) => {
218
+ const child = spawn('ssh', [...sshArgv(host), command], {
219
+ stdio: ['pipe', 'pipe', 'pipe'],
220
+ windowsHide: true,
221
+ })
222
+
223
+ const outChunks = []
224
+ const errChunks = []
225
+ let outBytes = 0
226
+ let settled = false
227
+ let timer = null
228
+
229
+ const stdoutText = () => Buffer.concat(outChunks).toString('utf8')
230
+ const stderrText = () => Buffer.concat(errChunks).toString('utf8')
231
+
232
+ function done(fn, value) {
233
+ if (settled) return
234
+ settled = true
235
+ if (timer) { clearTimeout(timer); timer = null }
236
+ fn(value)
237
+ }
238
+
239
+ function fail(message, fields) {
240
+ const e = new Error(message)
241
+ Object.assign(e, fields)
242
+ done(reject, e)
243
+ }
244
+
245
+ // 见上面第 1 条:远端早退会让这里 EPIPE,宁可什么都没有也不能抛出去。
246
+ child.stdin.on('error', () => {})
247
+
248
+ child.stdout.on('data', (chunk) => {
249
+ if (settled) return
250
+ outBytes += chunk.length
251
+ outChunks.push(chunk)
252
+ if (outBytes > MAX_BUFFER) {
253
+ try { child.kill('SIGTERM') } catch { /* 已经退出了就算了 */ }
254
+ fail(`远端输出超过 ${MAX_BUFFER} 字节上限`, { code: 'too_big', stderr: stderrText(), timedOut: false })
255
+ }
256
+ })
257
+
258
+ child.stderr.on('data', (chunk) => { errChunks.push(chunk) })
259
+
260
+ timer = setTimeout(() => {
261
+ try { child.kill('SIGTERM') } catch { /* 同上 */ }
262
+ fail(`ssh 超时(${timeoutMs} ms)`, { code: null, stderr: stderrText(), timedOut: true })
263
+ }, timeoutMs)
264
+
265
+ child.on('error', (err) => {
266
+ // 子进程压根没起来(ssh 不在 PATH、别名解析失败):没有退出码,也没有 stderr。
267
+ fail(String(err?.message ?? err), { code: err?.code ?? null, stderr: stderrText(), timedOut: false })
268
+ })
269
+
270
+ child.on('close', (code) => {
271
+ if (settled) return
272
+ if (code === 0) { done(resolve, { stdout: stdoutText(), stderr: stderrText() }); return }
273
+ fail(`ssh 退出码 ${code}`, { code, stderr: stderrText(), timedOut: false })
274
+ })
275
+
276
+ const payload = Buffer.isBuffer(input) ? input : Buffer.from(String(input ?? ''), 'utf8')
277
+ try {
278
+ child.stdin.end(payload)
279
+ } catch {
280
+ // stdin 已随子进程销毁(极快的早退):同样交给退出码判定。
281
+ }
153
282
  })
154
283
  }
@@ -0,0 +1,358 @@
1
+ /**
2
+ * sync 层 —— **冲突裁决**(3.0.0 第 4 步的后端,`docs/3.0.0-arbitration-ui.md` §3.4)。
3
+ *
4
+ * 跨设备冲突的三条出路,这里各给一条实现:
5
+ *
6
+ * | 动作 | 写什么 | 基线怎么走 | 记录 |
7
+ * |---|---|---|---|
8
+ * | `local` | 本地版写远端(`overwrite`,走 `upload.js` 的协议) | 推进到**本地那份** | `resolved` + `decision:'local'` |
9
+ * | `remote` | 远端版写本地(带 `expectedRevision`) | 推进到**远端那份** | `resolved` + `decision:'remote'` |
10
+ * | `manual` | **一个字节都不写**(人自己改,改完重跑一次检查) | 不动 | `resolved` + `decision:'manual'` |
11
+ *
12
+ * ## 为什么「手工合并」不自动写
13
+ *
14
+ * 三方合并的坏结果不是报错,是「看起来对、其实改丢了半句」。让人自己改,插件只负责
15
+ * 把两份摆在他面前(设计稿 §3.4)。所以这条分支**连读都不读**:不读远端、不读本地、
16
+ * 不碰基线 —— 只把记录标成已裁决。
17
+ *
18
+ * ## 基线的三条纪律(与 `pull.js` ⑤ / `push.js` ⑧ 同一条,别在一处破例)
19
+ *
20
+ * 1. **只推进真的写成功的那些**。远端 STALE、本地 `stale_revision`、传输断、
21
+ * 远端脚本 FATAL —— 一律不动基线,且**记录保持 `open`**。推进了就等于「这件事处理过了」,
22
+ * 下次检查再也看不见它,而文件其实还是两份。
23
+ * 2. **读基线时用与 `pull.js` 同一份 `usable` 判据**:`stored.host` / `stored.remotePath`
24
+ * 与这次的远端对不上,就当**没有基线**(旧基线描述的是另一个库,拿它拼表会把
25
+ * 另一个库的 sha 记成「这台已经同步过」)。
26
+ * 3. **⚠️ 反向对照:不推基线 = 下次检查冲突复活。**
27
+ * 「留远端」把远端那份写进本地之后,本地 = 远端,唯独基线还停在**旧的第三份**上 ——
28
+ * 于是三方比对给出 `local: changed` + `remote: changed` = `both-changed`,同一条冲突
29
+ * 原样再长出来。人会觉得「修了没用」。`test/sync-arbitration-test.mjs` 的 U9 就是
30
+ * 把这句话写成一条会红的断言(基线写失败 → 冲突复活;写成功 → 变 `same`)。
31
+ *
32
+ * ## 本文件不碰的东西
33
+ *
34
+ * - **不拼 `sh -s`、不自己写一份上行逻辑**:上行只有 `upload.js` 的三件套
35
+ * (`encodeUploadBatch` / `buildUploadCommand` / `parseUploadOutput`)。
36
+ * 2026-12-05 真机七条用例全灭的根因就是「脚本 + 正文挤同一条 stdin」,见 `upload.js` 文件头。
37
+ * - **不直接调 DSH 网关**:本地写走注入的 `deps.writeMemory`(签名与 `pull.js` 一致),
38
+ * 拿不到写通道就 `unsupported` —— 一条记忆的落盘口径只该有一处。
39
+ * - **不发明新状态**:状态机与字段白名单都在 `memory/conflicts.js`(`patchConflict`)。
40
+ *
41
+ * ## 记录上的三个新字段是**只读**的
42
+ *
43
+ * `origin` / `host` / `remotePath` 由第 4 步的另一条线(拉取 / 推送侧)写进记录,本文件只读:
44
+ * 没有就按「缺失」处理(`origin` 缺失 → `not_sync`;`host` / `remotePath` 缺失 → 留本地时
45
+ * `no_remote`,留远端时基线没有归属对象 → 不写基线并报告 `baseError`)。
46
+ */
47
+ import { readFile } from 'node:fs/promises'
48
+ import { join } from 'node:path'
49
+ import { patchConflict as patchConflictImpl, readConflict as readConflictImpl } from '../memory/conflicts.js'
50
+ import { readBase, writeBase } from './base.js'
51
+ import { sha256Of } from './content.js'
52
+ import { remoteStateDirOf } from './gate.js'
53
+ import { isSafeSyncName } from './policy.js'
54
+ import { spawnSshInput } from './remote.js'
55
+ import { buildUploadCommand, encodeUploadBatch, parseUploadOutput } from './upload.js'
56
+
57
+ /**
58
+ * 三种裁决方式。**顺序即界面顺序**(留本地 / 留远端 / 手工合并),不是优先级。
59
+ *
60
+ * 判据是「内容往哪边落」:`local` = 保本地那份、写远端;`remote` = 保远端那份、写本地。
61
+ * 两个词说的都是**保留哪一份**,不是「操作谁」—— 界面上的按钮文案与这里必须同一个意思,
62
+ * 否则人会点反(这是这一屏唯一不可挽回的操作)。
63
+ */
64
+ export const RESOLVE_CHOICES = Object.freeze(['local', 'remote', 'manual'])
65
+
66
+ /**
67
+ * 推进基线(**只在一个文件真的写成功之后调**)。
68
+ *
69
+ * 复用 `pull.js` ⑤ 的三件事:读旧表 → 判 `usable` → 拼新表写回。判据逐字一致,
70
+ * 不在这里另立一套(两份 `usable` 会漂移,而漂移的后果是「另一台库的 sha 被当成这台已同步」)。
71
+ *
72
+ * @returns {Promise<{ok:true} | {ok:false, error:string}>} —— 失败只带文案,由调用方决定
73
+ * 要不要把它降级成 `baseError`(写成功这件事已经发生了,不能因为基线写不进去就说没写过)
74
+ */
75
+ async function advanceBase({ readBaseFn, writeBaseFn, stateRoot, record, file, sha, at }) {
76
+ let stored = null
77
+ try {
78
+ stored = await readBaseFn(stateRoot)
79
+ } catch {
80
+ // 读不出来就按「没有基线」处理:与 `base.js` 的「坏基线当没有基线」同一条纪律。
81
+ stored = null
82
+ }
83
+
84
+ // 远端身份:记录里的优先,其次沿用旧基线记着的那一对。两者都没有 = 这条基线没有归属对象。
85
+ const host = String(record?.host ?? '') || String(stored?.host ?? '')
86
+ const remotePath = String(record?.remotePath ?? '') || String(stored?.remotePath ?? '')
87
+ if (host === '' || remotePath === '') {
88
+ // **不写一份空身份的基线**:`usable` 判据里空 host / 空 remotePath 是通配符,
89
+ // 那样一次「不知道写到哪台」的裁决会让这台库的基线对**所有**远端生效。
90
+ return { ok: false, error: '记录里没有 host / remotePath,基线没有归属对象(没有写一份「任何远端都算数」的基线)' }
91
+ }
92
+
93
+ // 与 `pull.js` ⑤ 逐字同一份判据:对不上就当没有基线。
94
+ const usable = Boolean(stored)
95
+ && (!stored.host || stored.host === host)
96
+ && (!stored.remotePath || stored.remotePath === remotePath)
97
+ const files = new Map(usable ? stored.files : [])
98
+ files.set(file, sha)
99
+
100
+ try {
101
+ await writeBaseFn(stateRoot, { files, host, remotePath, at })
102
+ } catch (err) {
103
+ return { ok: false, error: `基线写不进去(${err?.code ?? err?.message ?? err})` }
104
+ }
105
+ return { ok: true }
106
+ }
107
+
108
+ /**
109
+ * 裁决一条跨设备冲突。
110
+ *
111
+ * 前置(任何 `choice` 之前,顺序固定):方式合法 → 记录读得出 → 记录还开着 →
112
+ * 这条确实是跨设备冲突 → (留本地时)知道远端是哪一台。任何一条不过就**什么都不写**。
113
+ *
114
+ * @param {object} input
115
+ * @param {string} input.id — 冲突 id
116
+ * @param {'local'|'remote'|'manual'} input.choice
117
+ * @param {string} input.memoryDir — 记忆目录(留本地时现读本地正文)
118
+ * @param {string} input.stateRoot — 状态根(冲突记录 / 基线)
119
+ * @param {number} [input.now] — 基线 `at` 用它(不自己读时钟,测试要能重放)
120
+ * @param {number} [input.timeoutMs] — ssh 整体超时
121
+ * @param {object} [input.deps] — 注入点(测试要能全假)
122
+ * @returns {Promise<{
123
+ * ok: boolean, code?: string, error?: string,
124
+ * choice: string, wrote: 'remote'|'local'|'none',
125
+ * baseUpdated: boolean, baseError?: string,
126
+ * status: string, recordId: string,
127
+ * }>}
128
+ */
129
+ export async function resolveSyncConflict({
130
+ id,
131
+ choice,
132
+ memoryDir,
133
+ stateRoot,
134
+ now = Date.now(),
135
+ timeoutMs,
136
+ deps = {},
137
+ }) {
138
+ const readConflictFn = deps.readConflict ?? readConflictImpl
139
+ const patchConflictFn = deps.patchConflict ?? patchConflictImpl
140
+ const readBaseFn = deps.readBase ?? readBase
141
+ const writeBaseFn = deps.writeBase ?? writeBase
142
+ // 留本地:本地正文**现读**(不用记录里的 `onDisk`)—— 人要保的是「现在盘上那一版」。
143
+ const readLocalFile = deps.readLocalFile ?? ((name) => readFile(join(memoryDir, name)))
144
+ // 留远端:本地写通道(与本文件不直接调网关,装配方注入)。
145
+ const writeMemory = deps.writeMemory
146
+ const sendUpload = deps.sendUpload ?? ((args) => spawnSshInput(args))
147
+ const buildUploadCommandFn = deps.buildUploadCommand ?? buildUploadCommand
148
+
149
+ const at = new Date(now).toISOString()
150
+ const timeout = Number.isFinite(timeoutMs) ? { timeoutMs } : {}
151
+ const recordId = typeof id === 'string' ? id : ''
152
+ const choiceText = String(choice ?? '')
153
+
154
+ /** 统一的结果形状:没写成功的东西一律 `wrote:'none'` / `baseUpdated:false`。 */
155
+ const echo = (extra) => ({
156
+ choice: choiceText,
157
+ wrote: 'none',
158
+ baseUpdated: false,
159
+ status: '',
160
+ recordId,
161
+ ...extra,
162
+ })
163
+ const bad = (code, detail, extra) => ({
164
+ ok: false,
165
+ ...echo(extra),
166
+ code,
167
+ error: `错误:${code} — ${detail}`,
168
+ })
169
+
170
+ // ── ① 方式合法 ──
171
+ if (!RESOLVE_CHOICES.includes(choiceText)) {
172
+ return bad('invalid', '未知的裁决方式')
173
+ }
174
+
175
+ // ── ② 记录读得出来(失败透传它的 code / error)──
176
+ const read = await readConflictFn(id, { stateRoot })
177
+ if (!read || read.ok !== true) {
178
+ return bad(read?.code ?? 'io_error', read?.error ?? '冲突记录读不出来')
179
+ }
180
+
181
+ const record = read.record ?? {}
182
+ const rid = String(record.id ?? recordId)
183
+ const status = String(record.status ?? '')
184
+ const origin = String(record.origin ?? '')
185
+ const file = String(record.file ?? '')
186
+ const host = String(record.host ?? '')
187
+ const remotePath = String(record.remotePath ?? '')
188
+ const known = { status, recordId: rid }
189
+
190
+ // ── ③ 还开着吗(状态机在 `conflicts.js`:已裁决的记录不许回到 open)──
191
+ if (status !== 'open') {
192
+ return bad('not_open', `这条已经裁决过了(状态 ${status || '未知'}),要重开请新建一条记录`, known)
193
+ }
194
+
195
+ // ── ④ 是不是跨设备冲突(`origin` 缺省按 `manual` 处理 —— 旧记录没有这个字段)──
196
+ if (origin !== 'sync') {
197
+ return bad('not_sync', '这条不是跨设备冲突,请到冲突队列里处理', known)
198
+ }
199
+
200
+ // ── ⑤ 手工合并:一个字节都不写 ──
201
+ if (choiceText === 'manual') {
202
+ const patched = await patchConflictFn(rid, { status: 'resolved', decision: 'manual' }, { stateRoot })
203
+ if (!patched?.ok) {
204
+ return bad(patched?.code ?? 'io_error', patched?.error ?? '冲突记录改不动', known)
205
+ }
206
+ return { ok: true, choice: choiceText, wrote: 'none', baseUpdated: false, status: 'resolved', recordId: rid }
207
+ }
208
+
209
+ // 留本地要往远端写:连「写到哪一台」都不知道就不该往下走(这条前置排在文件名之前 ——
210
+ // 契约里的五条前置顺序是固定的,多出来的守卫一律往后排)。
211
+ if (choiceText === 'local' && (host === '' || remotePath === '')) {
212
+ return bad('no_remote', '记录里没有 host / remotePath,不知道要写到哪台远端', known)
213
+ }
214
+
215
+ // 文件名来自记录(**外部输入**):单段 `.md` 才放行 —— 它会进 `join(memoryDir, file)`
216
+ // 与上行协议,一个 `../` 就够写到记忆目录之外。
217
+ if (!isSafeSyncName(file)) {
218
+ return bad('invalid', '记录里的文件名不安全(必须是单段 .md),已拒绝', known)
219
+ }
220
+
221
+ // ── ⑥1 留本地:本地版写远端 ──
222
+ if (choiceText === 'local') {
223
+ // 远端路径先算:配置错就是错,别在读过本地正文之后才发现(那时已经白读一次)。
224
+ let command
225
+ try {
226
+ command = buildUploadCommandFn({ remotePath, stateDir: remoteStateDirOf(remotePath) })
227
+ } catch (err) {
228
+ return bad('invalid', String(err?.message ?? err), known)
229
+ }
230
+
231
+ let buf
232
+ try {
233
+ const got = await readLocalFile(file)
234
+ buf = Buffer.isBuffer(got) ? got : Buffer.from(String(got ?? ''), 'utf8')
235
+ } catch (err) {
236
+ return bad('local_missing', `读不到本地原件(${err?.code ?? err?.message ?? err}),没有推任何东西`, known)
237
+ }
238
+
239
+ // `expect` 是**远端当前那份**的 sha(记录里的 `actualVersion`):远端在这期间又变过 → STALE,
240
+ // 一个字都不写。编码器自己算 `sha`(「传的是什么」与「声明的是什么」不许有两个来源)。
241
+ let encoded
242
+ try {
243
+ encoded = encodeUploadBatch({
244
+ items: [{ name: file, action: 'overwrite', content: buf, expect: String(record.actualVersion ?? '') }],
245
+ })
246
+ } catch (err) {
247
+ return bad('invalid', String(err?.message ?? err), known)
248
+ }
249
+
250
+ let res
251
+ try {
252
+ res = await sendUpload({ host, command, input: encoded.buffer, ...timeout })
253
+ } catch (err) {
254
+ const reason = err?.timedOut
255
+ ? '超时'
256
+ : String(err?.stderr ?? '').trim() || String(err?.message ?? err)
257
+ return bad('upload_failed', `上行没有走完(${reason})。远端脚本会自己清暂存区,远端记忆目录一个字节都没动`, known)
258
+ }
259
+
260
+ const parsed = parseUploadOutput(res?.stdout ?? '')
261
+ if (parsed.fatal !== null) {
262
+ return bad(
263
+ 'fatal',
264
+ `远端脚本在提交之前停下了(\`${parsed.fatal.code}\`${parsed.fatal.detail ? `:${parsed.fatal.detail}` : ''}),`
265
+ + '记忆目录一个字节都没动',
266
+ known,
267
+ )
268
+ }
269
+
270
+ const got = parsed.files.get(file)
271
+ if (!got) {
272
+ return bad('no_report', '远端没有回报这一条(脚本可能中途退出),按未写入处理', known)
273
+ }
274
+ if (got.status === 'stale_remote') {
275
+ return bad('stale_remote', '远端这一版在这期间又变过,没有覆盖(重跑一次检查即可)', known)
276
+ }
277
+ if (got.status === 'conflict') {
278
+ return bad('conflict', '远端已经有一份同名文件,覆盖被拒(远端比记录里的更新)', known)
279
+ }
280
+ if (got.status === 'failed') {
281
+ return bad('failed', `远端报告没写成功(${got.code ?? '未知原因'})`, known)
282
+ }
283
+ if (got.status !== 'overwritten' && got.status !== 'uploaded') {
284
+ return bad(got.code ?? 'unknown', '远端报告了这一条但没说成功', known)
285
+ }
286
+
287
+ // 写成功了才动基线。推上去的是**盘上那一份**,所以基线取编码器算出的那份 sha。
288
+ const sentSha = encoded.entries[0]?.sha ?? sha256Of(buf)
289
+ const advanced = await advanceBase({
290
+ readBaseFn, writeBaseFn, stateRoot, record, file, sha: sentSha, at,
291
+ })
292
+
293
+ const patched = await patchConflictFn(rid, { status: 'resolved', decision: 'local' }, { stateRoot })
294
+ if (!patched?.ok) {
295
+ // 远端已经写成功了 —— 不能因为记录改不动就说「没写过」。两件事分开报告。
296
+ return {
297
+ ok: false,
298
+ ...echo({ wrote: 'remote', baseUpdated: advanced.ok, status }),
299
+ ...(advanced.ok ? {} : { baseError: advanced.error }),
300
+ code: patched?.code ?? 'io_error',
301
+ error: `错误:${patched?.code ?? 'io_error'} — 远端已经写成,但冲突记录改不动(${patched?.error ?? '未知原因'});记录仍是 open`,
302
+ }
303
+ }
304
+ return {
305
+ ok: true,
306
+ choice: choiceText,
307
+ wrote: 'remote',
308
+ baseUpdated: advanced.ok,
309
+ ...(advanced.ok ? {} : { baseError: advanced.error }),
310
+ status: 'resolved',
311
+ recordId: rid,
312
+ }
313
+ }
314
+
315
+ // ── ⑥2 留远端:远端版写本地 ──
316
+ if (typeof writeMemory !== 'function') {
317
+ return bad('unsupported', '这次装配没给本地写入通道(deps.writeMemory),无法把远端版写进本地库', known)
318
+ }
319
+
320
+ const text = typeof record.incoming === 'string' ? record.incoming : ''
321
+ // `expectedRevision` = **冲突发生那一刻本地那一版**(记录里的 `expectedVersion`)。
322
+ // 盘上已经变了 → 宿主版本守卫会拒(`stale_revision`),那时一个字都不写、记录保持 open。
323
+ let written
324
+ try {
325
+ written = await writeMemory(file, text, { expectedRevision: String(record.expectedVersion ?? '') })
326
+ } catch (err) {
327
+ return bad('io_error', `本地写入抛了异常(${err?.code ?? err?.message ?? err}),记录保持 open`, known)
328
+ }
329
+ if (!written?.ok) {
330
+ return bad(written?.code ?? 'io_error', written?.error ?? '本地写入被拒绝', known)
331
+ }
332
+
333
+ const incomingSha = sha256Of(Buffer.from(text, 'utf8'))
334
+ const advanced = await advanceBase({
335
+ readBaseFn, writeBaseFn, stateRoot, record, file, sha: incomingSha, at,
336
+ })
337
+
338
+ const patched = await patchConflictFn(rid, { status: 'resolved', decision: 'remote' }, { stateRoot })
339
+ if (!patched?.ok) {
340
+ return {
341
+ ok: false,
342
+ ...echo({ wrote: 'local', baseUpdated: advanced.ok, status }),
343
+ ...(advanced.ok ? {} : { baseError: advanced.error }),
344
+ code: patched?.code ?? 'io_error',
345
+ error: `错误:${patched?.code ?? 'io_error'} — 本地已经写成,但冲突记录改不动(${patched?.error ?? '未知原因'});记录仍是 open`,
346
+ }
347
+ }
348
+
349
+ return {
350
+ ok: true,
351
+ choice: choiceText,
352
+ wrote: 'local',
353
+ baseUpdated: advanced.ok,
354
+ ...(advanced.ok ? {} : { baseError: advanced.error }),
355
+ status: 'resolved',
356
+ recordId: rid,
357
+ }
358
+ }