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.
- package/README.en.md +39 -2
- package/README.md +39 -2
- package/lib/assembly/tools-mount.js +4 -1
- package/lib/autodream/audit.js +27 -12
- package/lib/autodream/reconcile.js +11 -1
- package/lib/autodream/tools.js +14 -5
- package/lib/client.js +674 -0
- package/lib/index.js +89 -3
- package/lib/memory/access.js +50 -28
- package/lib/memory/archive.js +3 -3
- package/lib/memory/chunks.js +16 -3
- package/lib/memory/conflicts.js +53 -4
- package/lib/memory/reader.js +2 -2
- package/lib/memory/scan.js +3 -3
- package/lib/memory/search.js +3 -3
- package/lib/memory/write-protocol.js +19 -7
- package/lib/mirror/export.js +2 -2
- package/lib/mirror/policy.js +12 -0
- package/lib/settings.js +10 -2
- package/lib/shared/codes.js +28 -0
- package/lib/sync/base.js +124 -0
- package/lib/sync/gate.js +303 -0
- package/lib/sync/instance.js +138 -0
- package/lib/sync/policy.js +217 -0
- package/lib/sync/pull.js +6 -0
- package/lib/sync/push.js +522 -0
- package/lib/sync/remote.js +139 -10
- package/lib/sync/resolve.js +358 -0
- package/lib/sync/upload.js +372 -0
- package/lib/tools/sync-tool.js +127 -1
- package/lib/typert/schemas.js +38 -0
- package/lib/typert.host.js +16 -0
- package/package.json +1 -1
package/lib/sync/push.js
ADDED
|
@@ -0,0 +1,522 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* sync 层 —— **推送 wiring**(3.0.0)。跨设备第 3 步:把「本地动过」的文件搬到远端。
|
|
3
|
+
*
|
|
4
|
+
* 与 `pull.js` 严格对称:判据全在 `policy.js`(类别 → 动作)、`gate.js`(写入门)、
|
|
5
|
+
* `upload.js`(线格式),这里只做**顺序与错误处理**。
|
|
6
|
+
*
|
|
7
|
+
* 顺序是有意为之,五条都别调换:
|
|
8
|
+
*
|
|
9
|
+
* 1. **先探门**(一次 ssh)。门不过就停在这里 —— 连清单都不去读,因为「这个远端是不是
|
|
10
|
+
* 我的库」还没确定的时候,连读它都算越界(读清单会跑 `find`,那是别人的目录)。
|
|
11
|
+
* 2. **再看清楚**(`check.js`,第二次 ssh,只读)。复用 2.27.0 的整条链,基线不写。
|
|
12
|
+
* 3. **折成计划**。`deviceId` 变了的那一轮,基线当**不存在**(见下)。
|
|
13
|
+
* 4. **预演到此为止**。不带 `apply` 时,远端一个字节都没收、本地一个字节都没改。
|
|
14
|
+
* 5. **要动真格**才:取冲突项的远端正文 → 一次 ssh 灌完正文 → 落冲突记录 → 推基线。
|
|
15
|
+
*
|
|
16
|
+
* 基线的三条纪律(与拉取共用,别在一处破例):
|
|
17
|
+
* - **只在真的写成功之后推进**。`upload` 撞名、`stale_remote`、失败 —— 都不推基线。
|
|
18
|
+
* 推进了就等于「这件事处理过了」,下次检查再也看不见它,而远端其实没变。
|
|
19
|
+
* - **推进的是「远端现在是什么」**。推成功的文件,远端内容 = 本地刚发过去的字节,
|
|
20
|
+
* 所以基线取的是**编码器算出的那份 sha**,不是分类时看到的那份。两者正常情况下相等,
|
|
21
|
+
* 但只有前者是「实际发出去的」。
|
|
22
|
+
* - **换库就清零**。`device_changed` 那一轮把旧基线当不存在 —— 旧基线描述的是另一个库,
|
|
23
|
+
* 拿它来分类会把「两边都不一样」读成「远端没动过」,那是推送最危险的一种误判。
|
|
24
|
+
* (真正兜底的是远端那侧的 revision 复核,基线只是第一道。)
|
|
25
|
+
*/
|
|
26
|
+
import { readFile } from 'node:fs/promises'
|
|
27
|
+
import { join } from 'node:path'
|
|
28
|
+
import { buildConflict, listConflicts, sameConflict, writeConflict } from '../memory/conflicts.js'
|
|
29
|
+
import { readBase, readConfirmedRemote, rememberConfirmedRemote, writeBase } from './base.js'
|
|
30
|
+
import { runSyncCheck } from './check.js'
|
|
31
|
+
import { fetchRemoteContents, sha256Of } from './content.js'
|
|
32
|
+
import { GATE_REASON_HINT, GATE_REASON_LABEL, gateVerdict, remoteStateDirOf } from './gate.js'
|
|
33
|
+
import { ensureLocalInstance, readRemoteInstance } from './instance.js'
|
|
34
|
+
import { planPush, pushSummary, renderPushReport } from './policy.js'
|
|
35
|
+
import { spawnSshInput, DEFAULT_TIMEOUT_MS } from './remote.js'
|
|
36
|
+
import { buildUploadCommand, encodeUploadBatch, parseUploadOutput } from './upload.js'
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 一次推送最多处理多少个文件。
|
|
40
|
+
*
|
|
41
|
+
* 与拉取的 `MAX_PULL_FILES` 同一个理由:这不是性能上限,是**防呆**。慢链路上一次推
|
|
42
|
+
* 几百个文件必然超时,而超时之后的半完成状态最难排查(远端进去了一部分,报告没生成)。
|
|
43
|
+
* 撞上这条说明用法不对 —— 整库搬迁该用 `scp -r` 明确做一次。
|
|
44
|
+
*/
|
|
45
|
+
export const MAX_PUSH_FILES = 50
|
|
46
|
+
|
|
47
|
+
/** 一次推送的字节上限。记忆条目上限 512 KB,50 个正常文件远到不了 20 MB。 */
|
|
48
|
+
export const MAX_PUSH_BYTES = 20 * 1024 * 1024
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 跑一次跨设备推送。
|
|
52
|
+
*
|
|
53
|
+
* @param {object} input
|
|
54
|
+
* @param {string} input.memoryDir — 记忆目录(只读)
|
|
55
|
+
* @param {string} input.stateRoot — 状态根(基线 / 冲突 / 身份)
|
|
56
|
+
* @param {string} input.host — ssh 主机别名
|
|
57
|
+
* @param {string} input.remotePath — 远端记忆目录
|
|
58
|
+
* @param {boolean} [input.confirm=false] — 首次 / 换库时的人点头
|
|
59
|
+
* @param {boolean} [input.apply=false] — 默认预演
|
|
60
|
+
* @param {number} [input.now]
|
|
61
|
+
* @param {number} [input.timeoutMs]
|
|
62
|
+
* @param {object} [input.deps] — 注入点(测试用)
|
|
63
|
+
* @returns {Promise<object>}
|
|
64
|
+
*/
|
|
65
|
+
export async function runSyncPush({
|
|
66
|
+
memoryDir,
|
|
67
|
+
stateRoot,
|
|
68
|
+
host,
|
|
69
|
+
remotePath,
|
|
70
|
+
confirm = false,
|
|
71
|
+
apply = false,
|
|
72
|
+
now = Date.now(),
|
|
73
|
+
timeoutMs,
|
|
74
|
+
deps = {},
|
|
75
|
+
}) {
|
|
76
|
+
const at = new Date(now).toISOString()
|
|
77
|
+
// 配置错误(空路径 / 相对路径 / 控制字符)一律在这里抛,与 `check.js` / `pull.js` 同口径。
|
|
78
|
+
const stateDir = remoteStateDirOf(remotePath)
|
|
79
|
+
|
|
80
|
+
const probeRemote = deps.readRemoteInstance ?? readRemoteInstance
|
|
81
|
+
const checkRemote = deps.runSyncCheck ?? runSyncCheck
|
|
82
|
+
const readBaseFn = deps.readBase ?? readBase
|
|
83
|
+
const writeBaseFn = deps.writeBase ?? writeBase
|
|
84
|
+
const readConfirmedFn = deps.readConfirmedRemote ?? readConfirmedRemote
|
|
85
|
+
const rememberFn = deps.rememberConfirmedRemote ?? rememberConfirmedRemote
|
|
86
|
+
const sendUpload = deps.sendUpload ?? ((args) => spawnSshInput(args))
|
|
87
|
+
const fetchContents = deps.fetchContents ?? fetchRemoteContents
|
|
88
|
+
const ensureInstance = deps.ensureLocalInstance ?? ensureLocalInstance
|
|
89
|
+
const buildConflictFn = deps.buildConflict ?? buildConflict
|
|
90
|
+
const writeConflictFn = deps.writeConflict ?? writeConflict
|
|
91
|
+
const listConflictsFn = deps.listConflicts ?? listConflicts
|
|
92
|
+
const sameConflictFn = deps.sameConflict ?? sameConflict
|
|
93
|
+
const readLocalFile = deps.readLocalFile ?? ((name) => readFile(join(memoryDir, name)))
|
|
94
|
+
const timeout = Number.isFinite(timeoutMs) ? { timeoutMs } : {}
|
|
95
|
+
|
|
96
|
+
const gateLabel = GATE_REASON_LABEL
|
|
97
|
+
const gateHint = GATE_REASON_HINT
|
|
98
|
+
|
|
99
|
+
const base = {
|
|
100
|
+
ok: true,
|
|
101
|
+
at,
|
|
102
|
+
host,
|
|
103
|
+
remotePath,
|
|
104
|
+
stateDir,
|
|
105
|
+
hasBase: false,
|
|
106
|
+
applied: false,
|
|
107
|
+
confirmed: false,
|
|
108
|
+
baseUpdated: false,
|
|
109
|
+
plan: [],
|
|
110
|
+
summary: { upload: 0, overwrite: 0, conflict: 0, skip: 0, total: 0 },
|
|
111
|
+
bytes: 0,
|
|
112
|
+
results: [],
|
|
113
|
+
skippedRemote: 0,
|
|
114
|
+
skippedLocal: 0,
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// ── ① 探门(一次 ssh)──
|
|
118
|
+
const probe = await probeRemote({
|
|
119
|
+
host,
|
|
120
|
+
remotePath,
|
|
121
|
+
...timeout,
|
|
122
|
+
...(deps.remoteRun ? { run: deps.remoteRun } : {}),
|
|
123
|
+
})
|
|
124
|
+
const known = await readConfirmedFn(stateRoot, { host, remotePath })
|
|
125
|
+
const verdict = gateVerdict({
|
|
126
|
+
hasStateDir: probe.hasStateDir,
|
|
127
|
+
instanceText: probe.instanceText,
|
|
128
|
+
knownDeviceId: known?.deviceId ?? null,
|
|
129
|
+
confirmed: known !== null,
|
|
130
|
+
confirmFlag: confirm === true,
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
const withGate = {
|
|
134
|
+
...base,
|
|
135
|
+
gate: verdict,
|
|
136
|
+
gateLabel: gateLabel[verdict.reason] ?? verdict.reason,
|
|
137
|
+
gateHint: gateHint[verdict.reason] ?? '',
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// 硬闸拦下:连清单都不读(见文件头第 1 条)。
|
|
141
|
+
if (!verdict.allow && !verdict.needConfirm) {
|
|
142
|
+
const reason = withGate.gateLabel
|
|
143
|
+
return {
|
|
144
|
+
...withGate,
|
|
145
|
+
ok: false,
|
|
146
|
+
code: 'gate',
|
|
147
|
+
reason: verdict.reason,
|
|
148
|
+
error: `错误:gate — ${reason}。${withGate.gateHint}`,
|
|
149
|
+
report: renderPushReport({
|
|
150
|
+
plan: [], host, remotePath, at, apply: false, hasBase: false,
|
|
151
|
+
gate: verdict, gateLabel: withGate.gateLabel, gateHint: withGate.gateHint,
|
|
152
|
+
}),
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// ── ② 看清楚(第二次 ssh;`device_changed` 时旧基线一律当不存在)──
|
|
157
|
+
const check = await checkRemote({
|
|
158
|
+
memoryDir,
|
|
159
|
+
stateRoot,
|
|
160
|
+
host,
|
|
161
|
+
remotePath,
|
|
162
|
+
updateBase: false,
|
|
163
|
+
now,
|
|
164
|
+
...(Number.isFinite(timeoutMs) ? { timeoutMs } : {}),
|
|
165
|
+
deps: {
|
|
166
|
+
fetchRemoteManifest: deps.fetchRemoteManifest,
|
|
167
|
+
localManifest: deps.localManifest,
|
|
168
|
+
// 换库那一轮:基线描述的是**另一个库**,拿它分类会把「两边都不一样」读成
|
|
169
|
+
// 「远端没动过」→ 覆盖掉远端的新版本。宁可多报一堆「两侧各自新增」,也不能误判。
|
|
170
|
+
readBase: verdict.reason === 'device_changed' ? async () => null : readBaseFn,
|
|
171
|
+
writeBase: writeBaseFn,
|
|
172
|
+
remoteRun: deps.remoteRun,
|
|
173
|
+
},
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
// ── ③ 折成计划 ──
|
|
177
|
+
const plan = planPush(check.result)
|
|
178
|
+
const summary = pushSummary(plan)
|
|
179
|
+
const todo = plan.filter((p) => p.action !== 'skip')
|
|
180
|
+
|
|
181
|
+
// 要读的本地正文:只有 upload / overwrite 两类。
|
|
182
|
+
// 预演也读一遍 —— 报告要报「总字节多少」,而这个数字只有真读文件才算得准(stat 也能,
|
|
183
|
+
// 但要再引一个依赖,看不出更好)。
|
|
184
|
+
const contents = new Map()
|
|
185
|
+
const localProblems = new Map()
|
|
186
|
+
for (const item of todo) {
|
|
187
|
+
if (item.action === 'conflict') continue
|
|
188
|
+
let buf
|
|
189
|
+
try {
|
|
190
|
+
buf = await readLocalFile(item.name)
|
|
191
|
+
} catch (err) {
|
|
192
|
+
localProblems.set(item.name, {
|
|
193
|
+
name: item.name,
|
|
194
|
+
status: 'failed',
|
|
195
|
+
code: 'io_error',
|
|
196
|
+
error: `读不到本地原件(${err?.code ?? err?.message ?? err})`,
|
|
197
|
+
})
|
|
198
|
+
continue
|
|
199
|
+
}
|
|
200
|
+
if (!Buffer.isBuffer(buf)) buf = Buffer.from(String(buf ?? ''), 'utf8')
|
|
201
|
+
// 分类时看到的是**报告那一刻**的本地 sha;这里是「现在」的字节。两者不等说明
|
|
202
|
+
// 文件在这中间被改过 —— 预演里没有它,就不该把它推出去(与拉取的 stale_remote 同一条纪律)。
|
|
203
|
+
if (sha256Of(buf) !== item.local) {
|
|
204
|
+
localProblems.set(item.name, {
|
|
205
|
+
name: item.name,
|
|
206
|
+
status: 'failed',
|
|
207
|
+
code: 'stale_local',
|
|
208
|
+
error: '本地文件在报告之后又被改过,本条未推送(重跑一次即可)',
|
|
209
|
+
})
|
|
210
|
+
continue
|
|
211
|
+
}
|
|
212
|
+
contents.set(item.name, buf)
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const uploadable = todo.filter((p) => p.action !== 'conflict' && contents.has(p.name))
|
|
216
|
+
const bytes = uploadable.reduce((n, p) => n + contents.get(p.name).length, 0)
|
|
217
|
+
|
|
218
|
+
const middle = {
|
|
219
|
+
...withGate,
|
|
220
|
+
hasBase: check.hasBase,
|
|
221
|
+
plan,
|
|
222
|
+
summary,
|
|
223
|
+
bytes,
|
|
224
|
+
skippedRemote: check.skippedRemote,
|
|
225
|
+
skippedLocal: check.skippedLocal,
|
|
226
|
+
}
|
|
227
|
+
const reportBase = {
|
|
228
|
+
plan,
|
|
229
|
+
host,
|
|
230
|
+
remotePath,
|
|
231
|
+
at,
|
|
232
|
+
apply,
|
|
233
|
+
hasBase: check.hasBase,
|
|
234
|
+
gate: verdict,
|
|
235
|
+
gateLabel: withGate.gateLabel,
|
|
236
|
+
gateHint: withGate.gateHint,
|
|
237
|
+
skippedRemote: check.skippedRemote,
|
|
238
|
+
skippedLocal: check.skippedLocal,
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// ── ④ 预演:到此为止 ──
|
|
242
|
+
if (!apply) {
|
|
243
|
+
return {
|
|
244
|
+
...middle,
|
|
245
|
+
report: renderPushReport({
|
|
246
|
+
...reportBase,
|
|
247
|
+
results: [...localProblems.values()],
|
|
248
|
+
bytes,
|
|
249
|
+
}),
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// 需要人点头但没点头:把计划念一遍(让人看清会推什么),然后**一个字都不发**。
|
|
254
|
+
// 注意顺序:预演(`!apply`)走的是上面那条路,它不算「没点头」—— 看计划本来就不需要点头。
|
|
255
|
+
if (!verdict.allow) {
|
|
256
|
+
return {
|
|
257
|
+
...middle,
|
|
258
|
+
ok: false,
|
|
259
|
+
code: 'need_confirm',
|
|
260
|
+
reason: verdict.reason,
|
|
261
|
+
error: `错误:need_confirm — ${withGate.gateLabel}。${withGate.gateHint}`,
|
|
262
|
+
report: renderPushReport({ ...reportBase, results: [...localProblems.values()], bytes }),
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// 确认痕迹**只在这里**写(`apply` + `confirm`)—— 一次预演不该产生信任。
|
|
267
|
+
if (confirm === true) {
|
|
268
|
+
await rememberFn(stateRoot, { host, remotePath, deviceId: verdict.deviceId, at })
|
|
269
|
+
}
|
|
270
|
+
// 本机身份:推送成功之后,别的机器会来读这份文件认我们。写不进去不阻断推送。
|
|
271
|
+
await ensureInstance(stateRoot, { at })
|
|
272
|
+
|
|
273
|
+
// ── ⑤ 上限(只在真动手时判 —— 预演拒绝预演没有意义)──
|
|
274
|
+
if (todo.length > MAX_PUSH_FILES || bytes > MAX_PUSH_BYTES) {
|
|
275
|
+
const why = todo.length > MAX_PUSH_FILES
|
|
276
|
+
? `${todo.length} 个文件 > 单次上限 ${MAX_PUSH_FILES}`
|
|
277
|
+
: `${bytes} 字节 > 单次上限 ${MAX_PUSH_BYTES}`
|
|
278
|
+
return {
|
|
279
|
+
...middle,
|
|
280
|
+
ok: false,
|
|
281
|
+
code: todo.length > MAX_PUSH_FILES ? 'too_many' : 'too_big',
|
|
282
|
+
error: `错误:${todo.length > MAX_PUSH_FILES ? 'too_many' : 'too_big'} — ${why}。`
|
|
283
|
+
+ '整库首次搬迁请用 `scp -r` 明确做一次,别走增量同步。',
|
|
284
|
+
report: renderPushReport({ ...reportBase, results: [...localProblems.values()], bytes }),
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const results = [...localProblems.values()]
|
|
289
|
+
let baseUpdated = false
|
|
290
|
+
|
|
291
|
+
// 队列里挂着的 open 记录(同一条冲突每次跑都会造出新时间戳 id,光靠 id 去重不够)。
|
|
292
|
+
const openConflicts = []
|
|
293
|
+
try {
|
|
294
|
+
const listed = await listConflictsFn({ stateRoot })
|
|
295
|
+
if (listed?.ok) openConflicts.push(...listed.items.filter((r) => r?.status === 'open'))
|
|
296
|
+
} catch {
|
|
297
|
+
// 读不出来就当没有:最坏后果是同一件事多一条记录,不会丢东西。
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** 记一条「两份都留下」。与 `pull.js` 的 `keepBoth` 同一个形状(UI 才能用同一套渲染)。 */
|
|
301
|
+
async function keepBoth({ name, remoteText, localText, expectSha, actualSha, note }) {
|
|
302
|
+
const record = buildConflictFn({
|
|
303
|
+
kind: 'external_change',
|
|
304
|
+
file: name,
|
|
305
|
+
incoming: String(remoteText ?? ''),
|
|
306
|
+
onDisk: String(localText ?? ''),
|
|
307
|
+
// 与拉取同一含义:expectedVersion = 本地那一版(对应 onDisk),actualVersion = 远端那一版。
|
|
308
|
+
expectedVersion: expectSha ?? '',
|
|
309
|
+
actualVersion: actualSha ?? '',
|
|
310
|
+
note: `跨设备同步(推送):两侧都动过,未覆盖远端${note ? `|${note}` : ''}`,
|
|
311
|
+
tool: 'memory_sync_push',
|
|
312
|
+
// 3.0.0:与 `pull.js` 同一套来源标注 —— 面板要靠它把「跨设备差异」挑出来。
|
|
313
|
+
origin: 'sync',
|
|
314
|
+
host,
|
|
315
|
+
remotePath,
|
|
316
|
+
at,
|
|
317
|
+
})
|
|
318
|
+
const twin = openConflicts.find((r) => sameConflictFn(r, record))
|
|
319
|
+
if (twin) return { ok: true, id: twin.id, reused: true }
|
|
320
|
+
|
|
321
|
+
const written = await writeConflictFn(record, { stateRoot })
|
|
322
|
+
if (!written?.ok) {
|
|
323
|
+
return { ok: false, code: written?.code ?? 'io_error', error: written?.error ?? '冲突记录写不进去' }
|
|
324
|
+
}
|
|
325
|
+
openConflicts.push(record)
|
|
326
|
+
return { ok: true, id: record.id }
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// ── ⑥ 冲突项:先把远端正文取回来(要留两份,就得有那两份的字节)──
|
|
330
|
+
const plannedConflicts = todo.filter((p) => p.action === 'conflict')
|
|
331
|
+
let conflictTexts = new Map()
|
|
332
|
+
if (plannedConflicts.length > 0) {
|
|
333
|
+
conflictTexts = await fetchContents({
|
|
334
|
+
host,
|
|
335
|
+
remotePath,
|
|
336
|
+
names: plannedConflicts.map((p) => p.name),
|
|
337
|
+
...timeout,
|
|
338
|
+
...(deps.contentRun ? { run: deps.contentRun } : {}),
|
|
339
|
+
})
|
|
340
|
+
}
|
|
341
|
+
for (const item of plannedConflicts) {
|
|
342
|
+
const got = conflictTexts?.get?.(item.name)
|
|
343
|
+
if (!got || !got.ok) {
|
|
344
|
+
results.push({
|
|
345
|
+
name: item.name,
|
|
346
|
+
status: 'failed',
|
|
347
|
+
code: got?.code ?? 'io_error',
|
|
348
|
+
error: got?.error ?? '取不到远端正文,没有建冲突记录(远端那份仍在原处)',
|
|
349
|
+
})
|
|
350
|
+
continue
|
|
351
|
+
}
|
|
352
|
+
// 本地那份现读(而不是用分类时读到的):记录里的 `onDisk` 必须是我**现在**留给人裁决的
|
|
353
|
+
// 那一版。读不出来就留空 —— 空是事实(文件被删了),不是失败。
|
|
354
|
+
let localText = ''
|
|
355
|
+
try {
|
|
356
|
+
const buf = await readLocalFile(item.name)
|
|
357
|
+
localText = Buffer.isBuffer(buf) ? buf.toString('utf8') : String(buf ?? '')
|
|
358
|
+
} catch {
|
|
359
|
+
localText = ''
|
|
360
|
+
}
|
|
361
|
+
const kept = await keepBoth({
|
|
362
|
+
name: item.name,
|
|
363
|
+
remoteText: got.text,
|
|
364
|
+
localText,
|
|
365
|
+
expectSha: item.local,
|
|
366
|
+
actualSha: got.sha256,
|
|
367
|
+
note: got.sha256 !== item.remote ? '远端在检查之后又变过(记录的是最新那份的哈希)' : '',
|
|
368
|
+
})
|
|
369
|
+
results.push(kept.ok
|
|
370
|
+
? { name: item.name, status: 'conflict', conflictId: kept.id }
|
|
371
|
+
: { name: item.name, status: 'failed', code: kept.code, error: kept.error })
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// ── ⑦ 一次 ssh 灌完正文(脚本走 argv、正文走 stdin)──
|
|
375
|
+
let parsed = null
|
|
376
|
+
const applied = []
|
|
377
|
+
if (uploadable.length > 0) {
|
|
378
|
+
const encoded = encodeUploadBatch({
|
|
379
|
+
items: uploadable.map((p) => ({
|
|
380
|
+
name: p.name,
|
|
381
|
+
action: p.action,
|
|
382
|
+
content: contents.get(p.name),
|
|
383
|
+
expect: p.remote,
|
|
384
|
+
})),
|
|
385
|
+
})
|
|
386
|
+
|
|
387
|
+
let out
|
|
388
|
+
try {
|
|
389
|
+
out = await sendUpload({
|
|
390
|
+
host: String(host).trim(),
|
|
391
|
+
// ⚠️ 别改成 `sh -s`:那是把脚本和正文塞进同一条 stdin,shell 解析器会把正文吃掉。
|
|
392
|
+
// 2026-12-05 真机七条用例全灭,根因就这一条(见 `upload.js` 文件头)。
|
|
393
|
+
command: buildUploadCommand({ remotePath, stateDir }),
|
|
394
|
+
input: encoded.buffer,
|
|
395
|
+
...timeout,
|
|
396
|
+
})
|
|
397
|
+
} catch (err) {
|
|
398
|
+
// 传输层失败 = **不知道远端进去了几个**。宁可报「什么都没确认」,也不猜。
|
|
399
|
+
const reason = err?.timedOut
|
|
400
|
+
? `超时(${timeout.timeoutMs ?? DEFAULT_TIMEOUT_MS} ms)`
|
|
401
|
+
: String(err?.stderr ?? '').trim() || String(err?.message ?? err)
|
|
402
|
+
return {
|
|
403
|
+
...middle,
|
|
404
|
+
ok: false,
|
|
405
|
+
code: 'upload_failed',
|
|
406
|
+
error: `错误:upload_failed — 上行没有走完(${reason})。`
|
|
407
|
+
+ '远端的暂存区会被脚本自己清掉;现在**不知道**有没有文件进去,重跑一次检查即可。',
|
|
408
|
+
results,
|
|
409
|
+
report: renderPushReport({ ...reportBase, results, bytes }),
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
parsed = parseUploadOutput(out?.stdout ?? '')
|
|
414
|
+
|
|
415
|
+
if (parsed.fatal !== null) {
|
|
416
|
+
return {
|
|
417
|
+
...middle,
|
|
418
|
+
ok: false,
|
|
419
|
+
code: 'upload_failed',
|
|
420
|
+
error: `错误:upload_failed — 远端脚本在提交之前停下了(\`${parsed.fatal.code}\`${parsed.fatal.detail ? `:${parsed.fatal.detail}` : ''})。`
|
|
421
|
+
+ '暂存区已清空,记忆目录**一个字节都没动**。',
|
|
422
|
+
results,
|
|
423
|
+
report: renderPushReport({ ...reportBase, results, bytes }),
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// 编码器算出的 sha 是「真正发出去的那份」,基线要用它。
|
|
428
|
+
const sent = new Map(encoded.entries.map((e) => [e.name, e]))
|
|
429
|
+
|
|
430
|
+
// 运行期间远端冒出来的同名文件(`local-new` 被判成已存在)也要留两份 —— 但我们
|
|
431
|
+
// 这时手里只有它的 sha,没有正文。取回来再建记录,代价是一次 ssh,而这种概率极低。
|
|
432
|
+
const raced = []
|
|
433
|
+
for (const e of encoded.entries) {
|
|
434
|
+
const got = parsed.files.get(e.name)
|
|
435
|
+
if (got?.status === 'conflict') raced.push(e.name)
|
|
436
|
+
}
|
|
437
|
+
let racedTexts = new Map()
|
|
438
|
+
if (raced.length > 0) {
|
|
439
|
+
racedTexts = await fetchContents({
|
|
440
|
+
host,
|
|
441
|
+
remotePath,
|
|
442
|
+
names: raced,
|
|
443
|
+
...timeout,
|
|
444
|
+
...(deps.contentRun ? { run: deps.contentRun } : {}),
|
|
445
|
+
})
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
for (const e of encoded.entries) {
|
|
449
|
+
const got = parsed.files.get(e.name)
|
|
450
|
+
const planItem = plan.find((p) => p.name === e.name)
|
|
451
|
+
if (!got) {
|
|
452
|
+
results.push({
|
|
453
|
+
name: e.name,
|
|
454
|
+
status: 'failed',
|
|
455
|
+
code: 'no_report',
|
|
456
|
+
error: '远端没有回报这一条(脚本可能中途退出),本条按未完成处理',
|
|
457
|
+
})
|
|
458
|
+
continue
|
|
459
|
+
}
|
|
460
|
+
if (got.status === 'uploaded' || got.status === 'overwritten') {
|
|
461
|
+
results.push({ name: e.name, status: got.status })
|
|
462
|
+
applied.push({ name: e.name, sha: sent.get(e.name)?.sha ?? e.sha })
|
|
463
|
+
continue
|
|
464
|
+
}
|
|
465
|
+
if (got.status === 'stale_remote') {
|
|
466
|
+
results.push({
|
|
467
|
+
name: e.name,
|
|
468
|
+
status: 'failed',
|
|
469
|
+
code: 'stale_remote',
|
|
470
|
+
error: '远端这一版在检查之后又变过,本条未覆盖(重跑一次检查即可)',
|
|
471
|
+
})
|
|
472
|
+
continue
|
|
473
|
+
}
|
|
474
|
+
if (got.status === 'conflict') {
|
|
475
|
+
const remoteGot = racedTexts?.get?.(e.name)
|
|
476
|
+
const kept = await keepBoth({
|
|
477
|
+
name: e.name,
|
|
478
|
+
remoteText: remoteGot?.ok ? remoteGot.text : '',
|
|
479
|
+
localText: contents.get(e.name)?.toString('utf8') ?? '',
|
|
480
|
+
expectSha: planItem?.local ?? '',
|
|
481
|
+
actualSha: remoteGot?.ok ? remoteGot.sha256 : (planItem?.remote ?? ''),
|
|
482
|
+
note: remoteGot?.ok ? '远端在推送期间冒出了同名文件' : '远端在推送期间冒出了同名文件(正文未取回)',
|
|
483
|
+
})
|
|
484
|
+
results.push(kept.ok
|
|
485
|
+
? { name: e.name, status: 'conflict', conflictId: kept.id }
|
|
486
|
+
: { name: e.name, status: 'failed', code: kept.code, error: kept.error })
|
|
487
|
+
continue
|
|
488
|
+
}
|
|
489
|
+
results.push({
|
|
490
|
+
name: e.name,
|
|
491
|
+
status: 'failed',
|
|
492
|
+
code: got.code ?? 'unknown',
|
|
493
|
+
error: '远端报告这一条没写成功',
|
|
494
|
+
})
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// ── ⑧ 基线:只推进真的写成功的那些 ──
|
|
498
|
+
if (applied.length > 0) {
|
|
499
|
+
const stored = await readBaseFn(stateRoot)
|
|
500
|
+
// `device_changed` 那一轮已经按「没有基线」分类过,这里也照办,不要拿旧表去拼。
|
|
501
|
+
const reusable = verdict.reason !== 'device_changed'
|
|
502
|
+
&& stored
|
|
503
|
+
&& (!stored.host || stored.host === host)
|
|
504
|
+
&& (!stored.remotePath || stored.remotePath === remotePath)
|
|
505
|
+
const files = new Map(reusable ? stored.files : [])
|
|
506
|
+
for (const d of applied) files.set(d.name, d.sha)
|
|
507
|
+
await writeBaseFn(stateRoot, { files, host, remotePath, at })
|
|
508
|
+
baseUpdated = true
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
const finished = {
|
|
513
|
+
...middle,
|
|
514
|
+
applied: true,
|
|
515
|
+
confirmed: confirm === true && verdict.allow,
|
|
516
|
+
baseUpdated,
|
|
517
|
+
results,
|
|
518
|
+
report: renderPushReport({ ...reportBase, results, bytes }),
|
|
519
|
+
}
|
|
520
|
+
if (parsed && parsed.unparsed > 0) finished.unparsedLines = parsed.unparsed
|
|
521
|
+
return finished
|
|
522
|
+
}
|