sage-mem 2.27.0 → 2.28.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 +25 -1
- package/README.md +25 -1
- package/lib/assembly/tools-mount.js +18 -2
- package/lib/index.js +1 -1
- package/lib/shared/codes.js +8 -0
- package/lib/sync/check.js +3 -1
- package/lib/sync/content.js +178 -0
- package/lib/sync/policy.js +175 -0
- package/lib/sync/pull.js +341 -0
- package/lib/sync/remote.js +56 -11
- package/lib/tools/sync-tool.js +128 -0
- package/package.json +1 -1
package/README.en.md
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
|
|
13
13
|
**Cross-session memory for DeepSeek Harness — plain markdown files, no database, no worker.**
|
|
14
14
|
|
|
15
|
-
**Current release: `2.
|
|
15
|
+
**Current release: `2.28.0`** — the npm badge above is the dynamic source of truth. **Contract baseline: `1.0.0`** — the first stable release, whose public commitments, the capability boundaries and the list of things it explicitly cannot do are frozen in the
|
|
16
16
|
[frozen contract](https://github.com/gezi-wen/sage-mem/blob/main/docs/1.0.0-contract.md).
|
|
17
17
|
|
|
18
18
|
If it is useful to you, a Star is the most direct feedback.
|
|
@@ -647,6 +647,30 @@ The remote side runs a single `find … -exec sha256sum {} +`; transport uses th
|
|
|
647
647
|
|
|
648
648
|
The **baseline** lives in `<state root>/sync/base.json`, **local only, never synced**. Without it you can only compare two sides blindly, which cannot tell "I changed it" from "it was always different". Once the differences are handled, run with `updateBase: true` to record the current state as the new baseline.
|
|
649
649
|
|
|
650
|
+
## Cross-device pull: fetch it in one ssh round trip (2.28.0)
|
|
651
|
+
|
|
652
|
+
`memory_sync_pull` moves files where **one side changed and the other did not** into the local main library. It **defaults to a dry run** - omit `apply` and nothing is touched:
|
|
653
|
+
|
|
654
|
+
```
|
|
655
|
+
memory_sync_pull({}) // dry run: report only, no content fetched, no writes, baseline untouched
|
|
656
|
+
memory_sync_pull({ apply: true }) // execute
|
|
657
|
+
```
|
|
658
|
+
|
|
659
|
+
| Class | What happens |
|
|
660
|
+
|---|---|
|
|
661
|
+
| remote new | created, plus one index line |
|
|
662
|
+
| remote changed only | local original **backed up first**, then overwritten under a version guard |
|
|
663
|
+
| both changed / both added with different content / locally deleted but remotely changed | **nothing is overwritten**: both bodies go into one conflict record, the remote body is kept in `<state root>/sync/incoming/` |
|
|
664
|
+
| local new / remote deleted / local deleted / inconsistent | reported only - **deletion is never automated** |
|
|
665
|
+
|
|
666
|
+
Three hard limits:
|
|
667
|
+
|
|
668
|
+
- **At most 50 files per run.** When the local library is nearly empty every remote file classifies as "remote new", which amounts to a first full migration - use `scp -r` explicitly for that.
|
|
669
|
+
- **Conflict items never advance the baseline.** Otherwise the next check would classify them as "local changed only" and the difference would become invisible. The cost is that the same conflict keeps being reported; the queue does not grow a duplicate (deduplicated by "is this the same conflict").
|
|
670
|
+
- **Pulled files get a fresh mtime.** They just arrived from the other machine, so counting them as fresh is fair.
|
|
671
|
+
|
|
672
|
+
Remote bodies are fetched in **a single ssh call** (`length line + raw bytes`, split by byte count), not one round trip per file - on a slow link that is the difference between "usable" and "timed out". Remote paths starting with `~` work as written.
|
|
673
|
+
|
|
650
674
|
## Configuration Reference
|
|
651
675
|
|
|
652
676
|
### Environment Variables
|
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
> File-based cross-session memory for DeepSeek Harness — every memory is a plain markdown file you can open, edit and delete. No database, no worker, no port.
|
|
16
16
|
|
|
17
|
-
**当前发布版本:`2.
|
|
17
|
+
**当前发布版本:`2.28.0`** —— 顶部 npm 徽章是动态权威。**契约基线:`1.0.0`** —— 第一个稳定版,公开承诺、能力边界与「明确做不到」的清单冻结在
|
|
18
18
|
[契约冻结](https://github.com/gezi-wen/sage-mem/blob/main/docs/1.0.0-contract.md)。
|
|
19
19
|
|
|
20
20
|
如果它对你有用,给个 Star 是最直接的反馈。
|
|
@@ -649,6 +649,30 @@ sage-mem 给记忆目录的写入加了**版本守卫**:写入前记下当前
|
|
|
649
649
|
|
|
650
650
|
**基线**落在 `<状态根>/sync/base.json`,**只在本机、不同步**。没有它就只能两边硬比,分不清「我改的」和「本来就不一样」。差异处理完之后,用 `updateBase: true` 跑一次,把现状记成新基线。
|
|
651
651
|
|
|
652
|
+
## 跨设备拉取:一次 ssh 搬回来(2.28.0)
|
|
653
|
+
|
|
654
|
+
`memory_sync_pull` 把「一侧动过、另一侧没动」的文件搬进本机主库。**默认预演** —— `apply` 不传就只看不动:
|
|
655
|
+
|
|
656
|
+
```
|
|
657
|
+
memory_sync_pull({}) // 预演:出清单,不拉正文、不写盘、不动基线
|
|
658
|
+
memory_sync_pull({ apply: true }) // 执行
|
|
659
|
+
```
|
|
660
|
+
|
|
661
|
+
| 类别 | 会做什么 |
|
|
662
|
+
|---|---|
|
|
663
|
+
| 远端新增 | 新建,并补一行索引 |
|
|
664
|
+
| 仅远端改 | **先备份**本地原件,再带版本守卫覆盖 |
|
|
665
|
+
| 两侧都改 / 两侧各自新增且不同 / 本地已删远端改过 | **谁都不覆盖**:两份正文进一条冲突记录,远端原件另存 `<状态根>/sync/incoming/` |
|
|
666
|
+
| 本地新增 / 远端已删 / 本地已删 / 数据不一致 | 只报告 —— **永不删除任何文件** |
|
|
667
|
+
|
|
668
|
+
三条硬约束:
|
|
669
|
+
|
|
670
|
+
- **单次最多 50 个文件**。本地库基本为空时远端全量都会被判「远端新增」,那等同于整库首次搬迁 —— 那种事请用 `scp -r` 明确做一次。
|
|
671
|
+
- **冲突项不推进基线**。否则下次检查会判成「仅本地改」,这个差异就再也看不见了。代价是每次检查都会再报同一条;队列里不会重复建(同一条冲突按「是不是同一件事」去重)。
|
|
672
|
+
- **被搬文件的 mtime 会刷新成现在**。它们刚从另一台机器过来,算新鲜是合理的。
|
|
673
|
+
|
|
674
|
+
远端正文**一次 ssh 全部取回**(`长度行 + 原样字节`,按字节切),不是每个文件一次往返 —— 在慢链路上这条差别就是「能用」与「超时」的差别。`~` 开头的远端目录也可以直接写。
|
|
675
|
+
|
|
652
676
|
## 配置参考
|
|
653
677
|
|
|
654
678
|
### 环境变量
|
|
@@ -19,12 +19,20 @@
|
|
|
19
19
|
* 是行不通的 —— 必须走 `ctx.inject`。
|
|
20
20
|
*/
|
|
21
21
|
import { createMemoryTools } from '../tools/memory-tools.js'
|
|
22
|
-
import { createSyncTool } from '../tools/sync-tool.js'
|
|
22
|
+
import { createSyncPullTool, createSyncTool } from '../tools/sync-tool.js'
|
|
23
23
|
import { readSyncSettings } from '../settings.js'
|
|
24
24
|
import { warnLog } from '../memory/util.js'
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
/**
|
|
27
|
+
* @param {object} ctx
|
|
28
|
+
* @param {{memory?: object}} [opts] — 2.28.0 追加:网关注入(`writeFile`)。
|
|
29
|
+
* 为什么走参数而不是 `ctx.get('memory')`:组合根构造 `MemoryGateway` 时**正在**注册
|
|
30
|
+
* 这个服务,此时用 `ctx.get` 读自己会拿到 undefined 或半成品;把 `this` 直接传进来
|
|
31
|
+
* 是唯一没有时序歧义的做法。
|
|
32
|
+
*/
|
|
33
|
+
export function mountMemoryTools(ctx, opts = {}) {
|
|
27
34
|
const state = { ready: false }
|
|
35
|
+
const memory = opts && typeof opts === 'object' ? opts.memory : null
|
|
28
36
|
try {
|
|
29
37
|
if (typeof ctx.inject === 'function') {
|
|
30
38
|
ctx.inject(['tools'], (inner) => {
|
|
@@ -38,6 +46,14 @@ export function mountMemoryTools(ctx) {
|
|
|
38
46
|
// 2.27.0:跨设备只读检查。与检索工具同一个注册窗口 —— 它不参与注入链,
|
|
39
47
|
// 少一个工具只是「模型少一条看差异的路」,不影响记忆照常注入。
|
|
40
48
|
inner.tools.register(createSyncTool({ readSettings: readSyncSettings }))
|
|
49
|
+
// 2.28.0:拉取。写入通道拿不到时**照样注册** —— 预演(不写盘)仍然可用,
|
|
50
|
+
// 真动手时才在工具里报 `unsupported`。少注册会让「看一眼有没有差异」也没得看。
|
|
51
|
+
inner.tools.register(createSyncPullTool({
|
|
52
|
+
readSettings: readSyncSettings,
|
|
53
|
+
writeMemory: typeof memory?.writeFile === 'function'
|
|
54
|
+
? (name, content, writeOpts) => memory.writeFile(name, content, writeOpts)
|
|
55
|
+
: undefined,
|
|
56
|
+
}))
|
|
41
57
|
state.ready = true
|
|
42
58
|
} catch (err) {
|
|
43
59
|
// 注册失败 ≠ 注入失败。出声一次,然后什么也不做。
|
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)
|
package/lib/shared/codes.js
CHANGED
|
@@ -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
|
+
}
|
package/lib/sync/policy.js
CHANGED
|
@@ -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:**校验判据只有一份**。
|
package/lib/sync/pull.js
ADDED
|
@@ -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
|
+
}
|
package/lib/sync/remote.js
CHANGED
|
@@ -13,12 +13,56 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import { execFile } from 'node:child_process'
|
|
15
15
|
|
|
16
|
-
/**
|
|
17
|
-
|
|
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
|
|
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 =
|
|
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
|
-
*
|
|
83
|
-
*
|
|
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
|
|
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)
|
package/lib/tools/sync-tool.js
CHANGED
|
@@ -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