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.
package/lib/index.js CHANGED
@@ -75,7 +75,7 @@ export class MemoryGateway extends TypertRemoteService {
75
75
  sessionsRoot: SESSIONS_ROOT,
76
76
  reservedFiles: [...RESERVED_FILES],
77
77
  })
78
- const tools = mountMemoryTools(ctx)
78
+ const tools = mountMemoryTools(ctx, { memory: this })
79
79
  mountObserve(ctx, MEMORY_DIR)
80
80
  // ⚠️ 写入门必须在 apply 里**同步**注册(见 lib/assembly/write-gate-mount.js 头注的「注册窗口」)。
81
81
  mountWriteGate(ctx, MEMORY_DIR)
@@ -80,6 +80,14 @@ export const CODES = Object.freeze({
80
80
  no_host: 'no_host',
81
81
  no_remote_path: 'no_remote_path',
82
82
  sync_failed: 'sync_failed',
83
+ // 2.28.0 拉取:拉回来的正文与清单里的 sha256 不符(传输截断 / 行尾转换 / 远端刚好在改)。
84
+ // 与 `stale_revision`(本地在报告之后被改过)分开:一个错在传输,一个错在并发。
85
+ stale_remote: 'stale_remote',
86
+ // 一次要搬的文件超过上限(本地库基本为空时会撞上)——「用法不对」不是「同步失败」。
87
+ too_many: 'too_many',
88
+ // 写协议已有的码(`write-protocol.js` 的 `ERR_ALREADY_EXISTS`);拉取把它当「降级成冲突」的信号,
89
+ // 所以这里必须能按值匹配。
90
+ already_exists: 'already_exists',
83
91
  // ── 其它 ──
84
92
  memory_unavailable: 'memory_unavailable',
85
93
  flood: 'flood',
package/lib/sync/check.js CHANGED
@@ -26,6 +26,7 @@ import { fetchRemoteManifest } from './remote.js'
26
26
  * @param {string} input.remotePath — 远端记忆目录
27
27
  * @param {boolean} [input.updateBase] — 显式要求才把本次远端清单记成新基线
28
28
  * @param {number} [input.now] — 时间戳(测试可注入)
29
+ * @param {number} [input.timeoutMs] — ssh 整体超时(默认见 `remote.js`;慢链路可放大)
29
30
  * @param {object} [input.deps] — 注入点,测试用来替掉 ssh / 磁盘
30
31
  * @returns {Promise<object>}
31
32
  */
@@ -36,10 +37,11 @@ export async function runSyncCheck({
36
37
  remotePath,
37
38
  updateBase = false,
38
39
  now = Date.now(),
40
+ timeoutMs,
39
41
  deps = {},
40
42
  }) {
41
43
  const remoteFetch =
42
- deps.fetchRemoteManifest ?? ((args) => fetchRemoteManifest({ ...args, run: deps.remoteRun }))
44
+ deps.fetchRemoteManifest ?? ((args) => fetchRemoteManifest({ ...args, run: deps.remoteRun, timeoutMs }))
43
45
  const localScan = deps.localManifest ?? localManifest
44
46
  const baseRead = deps.readBase ?? readBase
45
47
  const baseWrite = deps.writeBase ?? writeBase
@@ -0,0 +1,178 @@
1
+ /**
2
+ * sync 层 —— **远端正文**(IO,2.28.0)。
3
+ *
4
+ * 2.27.0 只拉清单(130 × 72 字节 ≈ 10 KB)。要搬文件就得把正文拉回来,
5
+ * 但**只拉需要处理的那些**:清单给了 sha256,能算出「哪几个文件值得占用带宽」。
6
+ *
7
+ * 四条纪律:
8
+ * 1. **一条 ssh 拉完全部正文**。2026-12-03 真机踩到:经 Tailscale 到一台自建主机
9
+ * 单次握手 5–20 秒且会抖动,每个文件一条命令时「第 3 次往返」就卡到超时。
10
+ * 把 N 次往返压成 1 次,是这个功能真实可用与否的分界。
11
+ * 2. **按字节比 sha256**。先解码成字符串再编回去,会在非法 UTF-8 上悄悄改写内容 ——
12
+ * 而 sha256 正是唯一的传输校验手段,改写了就再也验不出来。
13
+ * 3. **长度前缀而不是分隔符**。文件正文里出现分隔符只是时间问题;`wc -c` 给的是
14
+ * 字节数,按字节切永远对得上(文件末尾有没有换行都一样)。
15
+ * 4. **失败是值,不是异常**(除配置不合法外)。单个文件失败不该让整批失败 ——
16
+ * 其余文件照搬,报告点名这一个。
17
+ *
18
+ * 安全:文件名来自远端清单(**外部输入**),必须先过 `isSafeSyncName`;
19
+ * 远端目录与文件名进 shell 前都过 `quoteForShell`。
20
+ */
21
+ import { createHash } from 'node:crypto'
22
+ import { isSafeSyncName } from './policy.js'
23
+ import { DEFAULT_TIMEOUT_MS, quoteForShell, spawnSsh } from './remote.js'
24
+
25
+ /**
26
+ * 单个文件的字节上限。
27
+ *
28
+ * 记忆条目上限是 512 KB(注入侧的单文件上限),这里给 8 MB 是「正常文件绝不可能撞上、
29
+ * 但恶意大文件也进不来」的量级。超了不截断 —— 截断一份记忆等于悄悄改内容。
30
+ */
31
+ const MAX_CONTENT_BYTES = 8 * 1024 * 1024
32
+
33
+ /**
34
+ * 生成远端取正文的命令。
35
+ *
36
+ * 每个文件输出「长度行 + 原样字节」;文件不存在时输出 `ERR` 行(**不输出正文**),
37
+ * 这样后面文件的偏移量不会被带歪。
38
+ *
39
+ * @param {string} remotePath
40
+ * @param {string[]} names
41
+ * @returns {string}
42
+ */
43
+ export function buildContentsCommand(remotePath, names = []) {
44
+ const dir = quoteForShell(remotePath, '远端记忆目录')
45
+ const list = names.map((n) => quoteForShell(n, '文件名')).join(' ')
46
+ return `cd ${dir} && for f in ${list}; do `
47
+ + 'if [ -f "$f" ]; then printf \'%s\\n\' "$(wc -c < "$f")"; cat -- "$f"; else printf \'ERR\\n\'; fi; '
48
+ + 'done'
49
+ }
50
+
51
+ /**
52
+ * 批量拉正文。
53
+ *
54
+ * @param {object} input
55
+ * @param {string} input.host — `~/.ssh/config` 里的主机别名
56
+ * @param {string} input.remotePath — 远端记忆目录
57
+ * @param {string[]} input.names — 要拉的文件名(调用方已按分类筛过)
58
+ * @param {number} [input.timeoutMs]
59
+ * @param {Function} [input.run] — 注入点(测试用假执行器替换真 ssh)
60
+ * @returns {Promise<Map<string, {ok:true, text:string, sha256:string, bytes:number}
61
+ * | {ok:false, code:string, error:string}>>}
62
+ */
63
+ export async function fetchRemoteContents({ host, remotePath, names = [], timeoutMs = DEFAULT_TIMEOUT_MS, run = spawnSsh } = {}) {
64
+ const h = String(host ?? '').trim()
65
+ if (h === '') throw new Error('未配置远端主机(SSH 别名)')
66
+ if (/\s|[\0\n\r]/.test(h)) throw new Error('远端主机名不合法(含空白或控制字符)')
67
+
68
+ const out = new Map()
69
+ const safe = []
70
+ const canonical = new Map() // 归一后的名字 → 调用方给的原名(Map 的键必须与调用方一致)
71
+ for (const rawName of names) {
72
+ const name = String(rawName ?? '').trim()
73
+ if (!isSafeSyncName(name)) {
74
+ // 不安全的名字**不回显**原文:它可能就是那段 `../` 攻击串。
75
+ out.set(String(rawName ?? ''), { ok: false, code: 'invalid_name', error: '文件名不安全(非单段 .md),拒绝拉取' })
76
+ continue
77
+ }
78
+ safe.push(name)
79
+ canonical.set(name, String(rawName ?? ''))
80
+ }
81
+ if (safe.length === 0) return out
82
+
83
+ let res
84
+ try {
85
+ res = await run({
86
+ host: h,
87
+ command: buildContentsCommand(remotePath, safe),
88
+ timeoutMs,
89
+ encoding: 'buffer',
90
+ })
91
+ } catch (err) {
92
+ const stderr = textOf(err?.stderr).trim()
93
+ const reason = err?.timedOut ? `超时(${timeoutMs} ms)` : stderr || String(err?.message ?? err)
94
+ for (const name of safe) out.set(canonical.get(name) ?? name, { ok: false, code: 'io_error', error: `拉取失败:${reason}` })
95
+ return out
96
+ }
97
+
98
+ const buf = Buffer.isBuffer(res?.stdout) ? res.stdout : Buffer.from(textOf(res?.stdout), 'utf8')
99
+ // 整批没有任何字节 + 非空 stderr:`cd` 失败(目录填错 / 远端盘掉线)。
100
+ // 不能当成「每个文件都是空的」—— 空文件写进主库等于把一条记忆清空。
101
+ const stderr = textOf(res?.stderr).trim()
102
+ if (buf.length === 0 && stderr !== '') {
103
+ for (const name of safe) out.set(canonical.get(name) ?? name, { ok: false, code: 'io_error', error: `远端读不出来:${stderr}` })
104
+ return out
105
+ }
106
+
107
+ const raw = new Map()
108
+ parseStream(buf, safe, raw)
109
+ for (const [name, value] of raw) out.set(canonical.get(name) ?? name, value)
110
+ return out
111
+ }
112
+
113
+ /**
114
+ * 按「长度行 + 字节」切分流。
115
+ *
116
+ * 一旦对不上(找不到换行 / 长度不是数字 / 剩余字节不够),**从这一刻起后面全部记失败**:
117
+ * 偏移一旦错位,再猜就是拿错的字节当正文写进主库。
118
+ *
119
+ * @param {Buffer} buf
120
+ * @param {string[]} names
121
+ * @param {Map<string, object>} out
122
+ */
123
+ function parseStream(buf, names, out) {
124
+ let pos = 0
125
+ let broken = null
126
+ for (const name of names) {
127
+ if (broken) {
128
+ out.set(name, { ok: false, code: broken.code, error: broken.error })
129
+ continue
130
+ }
131
+ const nl = buf.indexOf(0x0a, pos)
132
+ if (nl < 0) {
133
+ broken = { code: 'io_error', error: '输出被截断(没读到长度行)' }
134
+ out.set(name, { ok: false, code: broken.code, error: broken.error })
135
+ continue
136
+ }
137
+ const line = buf.slice(pos, nl).toString('utf8').trim()
138
+ pos = nl + 1
139
+
140
+ if (line === 'ERR') {
141
+ out.set(name, { ok: false, code: 'io_error', error: '远端没有这个文件(拉取期间被删或改名)' })
142
+ continue
143
+ }
144
+ if (!/^\d+$/.test(line)) {
145
+ broken = { code: 'io_error', error: '输出无法解析(长度行不是数字)' }
146
+ out.set(name, { ok: false, code: broken.code, error: broken.error })
147
+ continue
148
+ }
149
+
150
+ const len = Number(line)
151
+ if (len > MAX_CONTENT_BYTES) {
152
+ broken = { code: 'too_big', error: `后面有一个文件超过 ${MAX_CONTENT_BYTES} 字节上限,整批无法定位` }
153
+ out.set(name, { ok: false, code: 'too_big', error: `单文件 ${len} 字节,超过 ${MAX_CONTENT_BYTES} 上限,未写入` })
154
+ continue
155
+ }
156
+ if (pos + len > buf.length) {
157
+ broken = { code: 'io_error', error: '输出被截断(正文不完整)' }
158
+ out.set(name, { ok: false, code: broken.code, error: broken.error })
159
+ continue
160
+ }
161
+
162
+ const chunk = buf.slice(pos, pos + len)
163
+ pos += len
164
+ out.set(name, { ok: true, text: chunk.toString('utf8'), sha256: sha256Of(chunk), bytes: chunk.length })
165
+ }
166
+ }
167
+
168
+ /** 按字节算 sha256(与 `manifest.js` / `sha256sum` 同口径)。 */
169
+ export function sha256Of(buf) {
170
+ return createHash('sha256').update(buf).digest('hex')
171
+ }
172
+
173
+ /** Buffer / 字符串 / undefined 统一成字符串(只为拼错误文案)。 */
174
+ function textOf(value) {
175
+ if (Buffer.isBuffer(value)) return value.toString('utf8')
176
+ if (value === undefined || value === null) return ''
177
+ return String(value)
178
+ }
@@ -233,6 +233,44 @@ export function parseRemoteManifest(text) {
233
233
  return { files, skipped }
234
234
  }
235
235
 
236
+ // ── 拉取(2.28.0)────────────────────────────────────────────────
237
+ //
238
+ // 「看清楚」(2.27.0)之后的第一步动手。判断只有一条:
239
+ // **一侧动过、另一侧没动 = 可以搬;两侧都动过 = 人的事。**
240
+ //
241
+ // 为什么把动作表放在这里而不是 wiring 里:分类与处置必须共用同一张表。
242
+ // 一旦 `pull.js` 里另写一份 if 链,`classifyOne` 改了而处置没改,就会
243
+ // 悄悄搬一个本该留给人裁决的文件 —— 这类漂移没有任何功能测试能抓到。
244
+
245
+ /** 一个文件在这次拉取里能有的四种去向。 */
246
+ export const PULL_ACTIONS = ['import', 'overwrite', 'conflict', 'skip']
247
+
248
+ /**
249
+ * 类别 → 动作(**唯一真相**)。
250
+ *
251
+ * 三条判据写在这,别处不许再判:
252
+ * 1. `remote-new` 可以 import —— 本地根本没有这个文件,搬进来撞不到任何东西;
253
+ * 2. `remote-changed` 可以 overwrite —— 本地等于基线 = 本地没动过(写入时还会再核一次 revision);
254
+ * 3. 其余一律不动。删除**永不自动执行**(远端删了我也不删本地),`inconsistent` 是逻辑矛盾,
255
+ * 只报不猜。
256
+ */
257
+ export const PULL_ACTION_OF = Object.freeze({
258
+ same: 'skip',
259
+ 'remote-new': 'import',
260
+ 'local-new': 'skip',
261
+ 'remote-changed': 'overwrite',
262
+ 'local-changed': 'skip',
263
+ 'both-changed': 'conflict',
264
+ 'both-new-diverged': 'conflict',
265
+ 'local-deleted-remote-changed': 'conflict',
266
+ // 远端已经删了 → 它那份正文根本不存在,凑不出「两份」。这类只报告,
267
+ // 由人决定是「按远端删掉本地」还是「把本地这份推回去」—— 两个动作都不该自动做。
268
+ 'local-changed-remote-deleted': 'skip',
269
+ 'remote-deleted': 'skip',
270
+ 'local-deleted': 'skip',
271
+ inconsistent: 'skip',
272
+ })
273
+
236
274
  /** 类别的中文短名(报告与面板共用一处,别各写各的)。 */
237
275
  export const CLASS_LABEL = {
238
276
  same: '一致',
@@ -334,6 +372,143 @@ function countOf(result, side) {
334
372
  return n
335
373
  }
336
374
 
375
+ /**
376
+ * 把分类结果折成「每个文件一行、带去向」的清单(纯函数)。
377
+ *
378
+ * 返回**全部**条目(含 `skip`):报告要把「我看见了但没动它」的也念出来,
379
+ * 否则「本地新增的没搬回来」会变成一个看不见的洞 —— 那正是 2.18 那条
380
+ * 「没写下来才叫遗漏」的同一个道理。
381
+ *
382
+ * @param {object} result — `classifySync()` 的返回值
383
+ * @returns {Array<{name:string, class:string, action:string, local?:string, remote?:string}>}
384
+ */
385
+ export function planPull(result) {
386
+ return (result?.entries ?? []).map((e) => ({
387
+ name: e.name,
388
+ class: e.class,
389
+ action: PULL_ACTION_OF[e.class] ?? 'skip',
390
+ local: e.local,
391
+ remote: e.remote,
392
+ }))
393
+ }
394
+
395
+ /** 按去向计数(报告抬头与工具回执共用)。 */
396
+ export function pullSummary(plan = []) {
397
+ const out = { import: 0, overwrite: 0, conflict: 0, skip: 0, total: 0 }
398
+ for (const item of plan) {
399
+ const a = PULL_ACTIONS.includes(item.action) ? item.action : 'skip'
400
+ out[a] += 1
401
+ out.total += 1
402
+ }
403
+ return out
404
+ }
405
+
406
+ /**
407
+ * 渲染拉取报告。
408
+ *
409
+ * 措辞纪律与 2.27.0 的只读报告一致:**只陈述做了什么、没做什么**。
410
+ * 差别只有一处 —— 这份报告在 `apply` 为真时说的是「已经发生的事」,
411
+ * 所以动词要换成完成式;预演时全部用「将要」。
412
+ *
413
+ * @param {object} input
414
+ * @param {Array} input.plan — `planPull()` 的结果
415
+ * @param {string} input.host
416
+ * @param {string} input.remotePath
417
+ * @param {string} [input.at]
418
+ * @param {boolean} [input.apply=false]
419
+ * @param {boolean} [input.hasBase=true]
420
+ * @param {Array<{name:string, status:string, code?:string, error?:string, conflictId?:string}>} [input.results]
421
+ * @param {number} [input.skippedRemote]
422
+ * @param {number} [input.skippedLocal]
423
+ * @returns {string}
424
+ */
425
+ export function renderPullReport({
426
+ plan = [],
427
+ host,
428
+ remotePath,
429
+ at,
430
+ apply = false,
431
+ hasBase = true,
432
+ results = [],
433
+ skippedRemote = 0,
434
+ skippedLocal = 0,
435
+ }) {
436
+ const summary = pullSummary(plan)
437
+ const busy = summary.total - summary.skip
438
+ const byName = new Map(results.map((r) => [r.name, r]))
439
+ const lines = []
440
+
441
+ lines.push(`# 跨设备同步 · 拉取报告(2.28.0)· ${apply ? '已执行' : '预演(dry-run)'}`)
442
+ lines.push('')
443
+ lines.push(`- 远端:\`${host}\` 的 \`${remotePath}\``)
444
+ if (at) lines.push(`- 生成时间:${at}`)
445
+ lines.push(`- 基线:${hasBase ? '有(上次同步的哈希表)' : '**无 —— 首次同步:只搬远端新增,不覆盖任何已有文件**'}`)
446
+ lines.push(`- 扫描:本地 ${plan.length} 个参与比对;远端清单跳过 ${skippedRemote} 条,本地跳过 ${skippedLocal} 个`)
447
+ lines.push('')
448
+
449
+ if (busy === 0) {
450
+ lines.push('**没有需要搬动的文件。**')
451
+ if (summary.skip > 0) lines.push('')
452
+ if (summary.skip > 0) lines.push(`> ${summary.skip} 个文件有差异但不该自动处理(见下),一个字节都没动。`)
453
+ lines.push('')
454
+ lines.push(apply ? '> 本次运行没有修改任何文件。' : '> 这是预演。加 `apply: true` 才会真的动手,但仍然只搬「一侧动过」的那些。')
455
+ return `${lines.join('\n')}\n`
456
+ }
457
+
458
+ lines.push(
459
+ `共 **${busy}** 个文件可以处理:搬入 **${summary.import}** / 覆盖 **${summary.overwrite}** / 留两份待裁决 **${summary.conflict}**;`
460
+ + `另有 **${summary.skip}** 个差异项不处理。`,
461
+ )
462
+ lines.push('')
463
+
464
+ const section = (title, action, note) => {
465
+ const names = plan.filter((p) => p.action === action).map((p) => p.name)
466
+ if (names.length === 0) return
467
+ lines.push(`## ${title}(${names.length})`)
468
+ lines.push('')
469
+ if (note) {
470
+ lines.push(`> ${note}`)
471
+ lines.push('')
472
+ }
473
+ for (const name of names) {
474
+ const r = byName.get(name)
475
+ lines.push(`- \`${name}\`${outcomeTail(r)}`)
476
+ }
477
+ lines.push('')
478
+ }
479
+
480
+ section('搬入(远端新增)', 'import', null)
481
+ section('覆盖(本地没动过)', 'overwrite', apply ? '> 覆盖前已把本地原件备份到 `<状态根>/sync/backup/`。' : '> 本地那份会先备份到 `<状态根>/sync/backup/`。')
482
+ section(
483
+ '留两份待裁决(两侧都动过)',
484
+ 'conflict',
485
+ '⚠️ 这些文件**没有**被任何一个版本覆盖。两份正文都写进了冲突记录,原件也另存一份;到「冲突」页签里裁决。',
486
+ )
487
+
488
+ const skipped = plan.filter((p) => p.action === 'skip' && p.class !== 'same')
489
+ if (skipped.length > 0) {
490
+ lines.push(`## 未处理(${skipped.length})`)
491
+ lines.push('')
492
+ lines.push('> 这些差异**按设计不自动处理**:删除永不自动执行,本地新增要推出去是第 3 步的事。')
493
+ lines.push('')
494
+ for (const p of skipped) lines.push(`- \`${p.name}\`(${CLASS_LABEL[p.class] ?? p.class})`)
495
+ lines.push('')
496
+ }
497
+
498
+ lines.push(apply
499
+ ? '> 本次运行只动了上面列出的文件;删除、索引重建、归档都没有发生。'
500
+ : '> 这是预演,**记忆目录一个字节都没改**。确认清单无误后加 `apply: true`。')
501
+ return `${lines.join('\n')}\n`
502
+ }
503
+
504
+ /** 一行尾巴:执行结果(冲突 / 失败)或空(成功与预演都不加尾巴)。 */
505
+ function outcomeTail(result) {
506
+ if (!result) return ''
507
+ if (result.status === 'conflict') return result.conflictId ? ` — 冲突记录 \`${result.conflictId}\`` : ' — 已留两份'
508
+ if (result.status === 'failed') return ` — **未处理**:\`${result.code ?? 'error'}\` ${result.error ?? ''}`.trimEnd()
509
+ return ''
510
+ }
511
+
337
512
  // ── 设置面(与 `mirror/policy.js` 的 resolveExternal / parseExternalPatch 对称)──
338
513
  //
339
514
  // 为什么放在 policy 里而不是 settings.js:**校验判据只有一份**。