sage-mem 2.26.0 → 2.27.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 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.26.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
15
+ **Current release: `2.27.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.
@@ -621,6 +621,32 @@ Rejecting **does not delete**: the original stays in `intake/agents/<source>/rej
621
621
 
622
622
  **Out of scope on purpose**: model-driven auto-merging, automatic rename deduplication, bulk approval (clicking one at a time is the physical guarantee behind "approve first, write later"); `intake/devices/` (cross-device) belongs to 4.0.0.
623
623
 
624
+ ## Cross-device check: see clearly before touching anything (2.27.0)
625
+
626
+ `memory_sync_check` runs a **read-only** three-way comparison: the remote memory directory's sha256 manifest against your local manifest and the **last sync baseline**.
627
+
628
+ It tells these apart - **only "one side changed, the other did not" is safe to carry over**:
629
+
630
+ | Class | Meaning |
631
+ |---|---|
632
+ | remote changed only / local changed only | the other side is untouched, safe to move |
633
+ | **both sides changed** ⚠️ | which one wins is a human decision; the tool will not pick |
634
+ | remote new / local new | an entry that exists on one side only |
635
+ | remote deleted / local deleted | safe only if the other side did not change it |
636
+ | **one deleted, one changed** ⚠️ | likewise a human decision |
637
+
638
+ **This release writes nothing**: no moving, no merging, no overwriting. It only answers "what differs".
639
+
640
+ Configure it in `settings.json`, or pass the values per call:
641
+
642
+ ```json
643
+ { "sync": { "host": "my-remote-host", "remotePath": "/home/you/memory" } }
644
+ ```
645
+
646
+ The remote side runs a single `find … -exec sha256sum {} +`; transport uses the ssh you already have - no new resident process.
647
+
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
+
624
650
  ## Configuration Reference
625
651
 
626
652
  ### 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.26.0`** —— 顶部 npm 徽章是动态权威。**契约基线:`1.0.0`** —— 第一个稳定版,公开承诺、能力边界与「明确做不到」的清单冻结在
17
+ **当前发布版本:`2.27.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 是最直接的反馈。
@@ -623,6 +623,32 @@ sage-mem 给记忆目录的写入加了**版本守卫**:写入前记下当前
623
623
 
624
624
  **明确不做**:模型参与的自动归并、自动改名去重、批量批准(一条条点,才是「先批后写」的物理保证);`intake/devices/`(跨设备)留给 4.0.0。
625
625
 
626
+ ## 跨设备检查:先看清楚,再动手(2.27.0)
627
+
628
+ `memory_sync_check` 跑一次**只读**检查:把远端记忆目录的 sha256 清单,与本地清单、以及**上次同步基线**做三方比对,报出差异类别。
629
+
630
+ 它分得清这几件事 —— **只有「一侧动过、另一侧没动」才适合搬运**:
631
+
632
+ | 类别 | 含义 |
633
+ |---|---|
634
+ | 仅远端改 / 仅本地改 | 另一侧没动过,可安全搬 |
635
+ | **两侧都改** ⚠️ | 谁赢是人的决定,工具不替你选 |
636
+ | 远端新增 / 本地新增 | 一侧独有的条目 |
637
+ | 远端已删 / 本地已删 | 另一侧没动过才安全 |
638
+ | **一侧删、一侧改** ⚠️ | 同样是人的决定 |
639
+
640
+ **这一版一个字节都不写**:不搬文件、不合并、不覆盖。它只回答「哪里不一样」。
641
+
642
+ 配置写在 `settings.json`,也可以每次传参:
643
+
644
+ ```json
645
+ { "sync": { "host": "my-remote-host", "remotePath": "/home/you/memory" } }
646
+ ```
647
+
648
+ 远端只跑一条 `find … -exec sha256sum {} +`,传输走已经装好的 ssh —— 没有新增常驻进程。
649
+
650
+ **基线**落在 `<状态根>/sync/base.json`,**只在本机、不同步**。没有它就只能两边硬比,分不清「我改的」和「本来就不一样」。差异处理完之后,用 `updateBase: true` 跑一次,把现状记成新基线。
651
+
626
652
  ## 配置参考
627
653
 
628
654
  ### 环境变量
@@ -19,6 +19,8 @@
19
19
  * 是行不通的 —— 必须走 `ctx.inject`。
20
20
  */
21
21
  import { createMemoryTools } from '../tools/memory-tools.js'
22
+ import { createSyncTool } from '../tools/sync-tool.js'
23
+ import { readSyncSettings } from '../settings.js'
22
24
  import { warnLog } from '../memory/util.js'
23
25
 
24
26
  export function mountMemoryTools(ctx) {
@@ -33,6 +35,9 @@ export function mountMemoryTools(ctx) {
33
35
  // 2.10.1:体积治理的模型入口。与检索工具同一个注册窗口 —— 缺它不会让注入链降级,
34
36
  // 只是模型少一条「把过大记忆裁小」的路(审计与做梦那边仍会照常提示)。
35
37
  inner.tools.register(trimMemory)
38
+ // 2.27.0:跨设备只读检查。与检索工具同一个注册窗口 —— 它不参与注入链,
39
+ // 少一个工具只是「模型少一条看差异的路」,不影响记忆照常注入。
40
+ inner.tools.register(createSyncTool({ readSettings: readSyncSettings }))
36
41
  state.ready = true
37
42
  } catch (err) {
38
43
  // 注册失败 ≠ 注入失败。出声一次,然后什么也不做。
package/lib/client.js CHANGED
@@ -4335,6 +4335,10 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
4335
4335
  "ext.what1": "开关打开后,白名单内的记忆会被复制到状态目录下的 mirror/ 里,其他 agent 通过 127.0.0.1 上的只读接口读那一份副本。",
4336
4336
  "ext.what2": "接口只有读:没有写入、不给文件路径、拿不到没勾选的条目。主库一个字都不会被它们改到。",
4337
4337
  "ext.status.on": "已开启 · 暴露 {count} 条",
4338
+ "ext.poll": "轮询间隔",
4339
+ "ext.unit.seconds": "秒",
4340
+ "ext.err.poll": "轮询间隔要填 15–600 的整数",
4341
+ "ext.notice.poll": "轮询间隔已保存",
4338
4342
  "ext.status.off": "关闭(默认)",
4339
4343
  "ext.prefixes": "按前缀整类开放",
4340
4344
  "ext.prefixesHint": "默认只开 project_ 与 reference_;user_ 与 feedback_ 是「关于我自己」的记忆,默认不给。",
@@ -5064,6 +5068,10 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
5064
5068
  "ext.what1": "When enabled, whitelisted memories are copied into mirror/ under the state directory, and other agents read that copy through a read-only endpoint on 127.0.0.1.",
5065
5069
  "ext.what2": "The endpoint can only read: no writes, no file paths, nothing outside the whitelist. Your main library is never modified by them.",
5066
5070
  "ext.status.on": "On · {count} exposed",
5071
+ "ext.poll": "Poll interval",
5072
+ "ext.unit.seconds": "s",
5073
+ "ext.err.poll": "Poll interval must be an integer between 15 and 600",
5074
+ "ext.notice.poll": "Poll interval saved",
5067
5075
  "ext.status.off": "Off (default)",
5068
5076
  "ext.prefixes": "Expose whole prefix groups",
5069
5077
  "ext.prefixesHint": "Only project_ and reference_ are on by default; user_ and feedback_ are memories about you and stay private.",
@@ -8036,6 +8044,7 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
8036
8044
  const sFiles = react.useState([]); const files = sFiles[0], setFiles = sFiles[1];
8037
8045
  const sTags = react.useState(""); const tagDraft = sTags[0], setTagDraft = sTags[1];
8038
8046
  const sPort = react.useState(""); const portDraft = sPort[0], setPortDraft = sPort[1];
8047
+ const sPoll = react.useState(""); const pollDraft = sPoll[0], setPollDraft = sPoll[1];
8039
8048
  const sBusy = react.useState(false); const busy = sBusy[0], setBusy = sBusy[1];
8040
8049
  const sErr = react.useState(null); const err = sErr[0], setErr = sErr[1];
8041
8050
  const sNotice = react.useState(""); const notice = sNotice[0], setNotice = sNotice[1];
@@ -8061,6 +8070,7 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
8061
8070
  const cur = d.external || {};
8062
8071
  setTagsOf(cur.tags);
8063
8072
  setPortDraft(String(typeof cur.port === "number" ? cur.port : ""));
8073
+ setPollDraft(String(typeof cur.pollSeconds === "number" ? cur.pollSeconds : ""));
8064
8074
  }, function (e) { setErr(String((e && e.message) || e)); });
8065
8075
  if (typeof remote.externalStatus === "function") {
8066
8076
  Promise.resolve(remote.externalStatus()).then(function (res) {
@@ -8090,6 +8100,7 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
8090
8100
  const cur = out.settings.external || {};
8091
8101
  setTagsOf(cur.tags);
8092
8102
  setPortDraft(String(typeof cur.port === "number" ? cur.port : ""));
8103
+ setPollDraft(String(typeof cur.pollSeconds === "number" ? cur.pollSeconds : ""));
8093
8104
  }
8094
8105
  // 保存完立刻重读状态:暴露条数与端点都要马上反映出来(宿主那边已经 refresh 过)。
8095
8106
  refreshStatus();
@@ -8149,6 +8160,14 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
8149
8160
  saveExternal({ port: n }, t("ext.notice.port"));
8150
8161
  }
8151
8162
 
8163
+ /** 轮询间隔(15–600 秒)。它是第二道保险:目录事件漏了也有它兜底。 */
8164
+ function savePoll() {
8165
+ const raw = String(pollDraft == null ? "" : pollDraft).trim();
8166
+ const n = Number(raw);
8167
+ if (raw === "" || !Number.isInteger(n) || n < 15 || n > 600) { setErr(t("ext.err.poll")); return; }
8168
+ saveExternal({ pollSeconds: n }, t("ext.notice.poll"));
8169
+ }
8170
+
8152
8171
  const statusText = busy
8153
8172
  ? t("lab.action.saving")
8154
8173
  : (enabled
@@ -8261,6 +8280,20 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
8261
8280
  disabled: busy || !memSet, onClick: savePort,
8262
8281
  }, busy ? t("lab.action.saving") : t("lab.action.save")),
8263
8282
  ]),
8283
+ h("div", { className: "smem-autodream-row", key: "poll" }, [
8284
+ h("span", { className: "smem-autodream-key", key: "k" }, t("ext.poll")),
8285
+ h("input", {
8286
+ className: "smem-input smem-num", key: "i", type: "number", min: 15, max: 600, step: 5,
8287
+ value: pollDraft,
8288
+ disabled: busy || !memSet,
8289
+ onChange: function (e) { setPollDraft(e.target.value); },
8290
+ }),
8291
+ h("span", { className: "smem-muted", key: "u" }, t("ext.unit.seconds")),
8292
+ h("button", {
8293
+ type: "button", className: "smem-btn smem-btn-primary", key: "save",
8294
+ disabled: busy || !memSet, onClick: savePoll,
8295
+ }, busy ? t("lab.action.saving") : t("lab.action.save")),
8296
+ ]),
8264
8297
  h("div", { className: "smem-autodream-note", key: "ep" }, t("ext.endpointLabel") + " " + endpointLine),
8265
8298
  h("div", { className: "smem-autodream-note", key: "last" }, lastLine),
8266
8299
  status && status.mirrorDir
package/lib/settings.js CHANGED
@@ -31,6 +31,7 @@ export { LIMIT_SPECS, MAX_RAW_BYTES }
31
31
  import { DEFAULT_CONFIG } from './autodream/config.js'
32
32
  import { readJson } from './autodream/util.js'
33
33
  import { parseExternalPatch, resolveExternal } from './mirror/policy.js'
34
+ import { parseSyncPatch, resolveSync } from './sync/policy.js'
34
35
  import { warnLog, writeFileAtomic } from './memory/util.js'
35
36
 
36
37
  /** 面板设置的落点:状态根下(与 autodream 的配置、台账同级)。 */
@@ -168,6 +169,16 @@ export async function readExternalSettings() {
168
169
  return resolveExternal(fileRead.data?.external)
169
170
  }
170
171
 
172
+ /**
173
+ * 读「跨设备同步」(2.27.0)的生效设置。工具 `memory_sync_check` 用它决定默认远端。
174
+ *
175
+ * @returns {Promise<{sync: {host: string, remotePath: string}, diagnostics: string[]}>}
176
+ */
177
+ export async function readSyncSettings() {
178
+ const fileRead = await readSettingsFileDetailed()
179
+ return resolveSync(fileRead.data?.sync)
180
+ }
181
+
171
182
  /**
172
183
  * 校验 `setSettings({ experimental })` 的那一段。
173
184
  *
@@ -273,6 +284,12 @@ export async function readSettingsSnapshot(ctx) {
273
284
  if (externalRead.diagnostics.length > 0) {
274
285
  warnLog(ctx, `外部访问设置有问题(本次按诊断后的值生效):${externalRead.diagnostics.join(';')}`)
275
286
  }
287
+ // 2.27.0:跨设备同步。与 external 同一套「面板保存后立刻生效」的语义 ——
288
+ // 每次跑检查时现读,不参与 restartRequired。
289
+ const syncRead = resolveSync(fileRead.data?.sync)
290
+ if (syncRead.diagnostics.length > 0) {
291
+ warnLog(ctx, `跨设备同步设置有问题(本次按诊断后的值生效):${syncRead.diagnostics.join(';')}`)
292
+ }
276
293
  // 模块加载时那份「用户声明的保护名」(RESERVED_FILES 里抠掉两个内置名)
277
294
  const activeExtra = [...RESERVED_FILES].filter((n) => n !== INDEX_FILE_KEY && n !== SESSION_LOG_KEY)
278
295
  const norm = (list) => JSON.stringify([...list].map((s) => String(s).toLowerCase()).sort())
@@ -302,6 +319,9 @@ export async function readSettingsSnapshot(ctx) {
302
319
  // 诊断非空时说明「你保存的值有一部分没被采纳,原因是 X」。
303
320
  external: externalRead.external,
304
321
  externalDiagnostics: externalRead.diagnostics,
322
+ // 2.27.0:跨设备同步的生效值与诊断。工具 `memory_sync_check` 拿它当默认远端。
323
+ sync: syncRead.sync,
324
+ syncDiagnostics: syncRead.diagnostics,
305
325
  }
306
326
  }
307
327
 
@@ -358,10 +378,14 @@ export async function applySettingsPatch(ctx, patch) {
358
378
  const extCheck = parseExternalPatch(p.external)
359
379
  if (!extCheck.ok) return { ok: false, error: extCheck.error }
360
380
  const extPatch = extCheck.patch
361
- if (!limitsPatch && nextReserved === null && uiPatch === null && labPatch === null && extPatch === null) return { ok: false, error: 'sage-mem: empty patch' }
381
+ // 2.27.0:跨设备同步 —— 同样「先全验、后一起写」,不认识的键直接拒。
382
+ const syncCheck = parseSyncPatch(p.sync)
383
+ if (!syncCheck.ok) return { ok: false, error: syncCheck.error }
384
+ const syncPatch = syncCheck.patch
385
+ if (!limitsPatch && nextReserved === null && uiPatch === null && labPatch === null && extPatch === null && syncPatch === null) return { ok: false, error: 'sage-mem: empty patch' }
362
386
 
363
387
  await mkdir(STATE_ROOT, { recursive: true })
364
- if (limitsPatch || uiPatch !== null || labPatch !== null || extPatch !== null) {
388
+ if (limitsPatch || uiPatch !== null || labPatch !== null || extPatch !== null || syncPatch !== null) {
365
389
  const currentRead = await readSettingsFileDetailed()
366
390
  // 坏文件上不写:没有可合并的旧值,整份重写会把用户手改的内容静默吞掉。
367
391
  // 明确拒绝、让用户先修文件,比「保存成功但别的设置都没了」诚实。
@@ -378,7 +402,9 @@ export async function applySettingsPatch(ctx, patch) {
378
402
  // 2.25.0:external 与上面三段同一套「没给就沿用文件里的有效值」。
379
403
  // ⚠️ 整份重写时必须把它带上 —— 否则保存一次 limits 会把 external 段静默抹掉。
380
404
  const mergedExternal = { ...resolveExternal(current?.external).external, ...(extPatch ?? {}) }
381
- await writeFileAtomic(SETTINGS_FILE, JSON.stringify({ limits: mergedLimits, experimental: mergedLab, ui: mergedUi, external: mergedExternal, updatedAt: Date.now() }, null, 2))
405
+ // 2.27.0:sync 同理 —— 整份重写时漏带它,保存一次 limits 就会把跨设备段抹掉。
406
+ const mergedSync = { ...resolveSync(current?.sync).sync, ...(syncPatch ?? {}) }
407
+ await writeFileAtomic(SETTINGS_FILE, JSON.stringify({ limits: mergedLimits, experimental: mergedLab, ui: mergedUi, external: mergedExternal, sync: mergedSync, updatedAt: Date.now() }, null, 2))
382
408
  }
383
409
  if (nextReserved !== null) {
384
410
  await writeFileAtomic(RESERVED_FILE, `${JSON.stringify(nextReserved, null, 2)}\n`)
@@ -76,6 +76,10 @@ export const CODES = Object.freeze({
76
76
  segment_too_small: 'segment_too_small',
77
77
  remain_too_small: 'remain_too_small',
78
78
  reason_too_short: 'reason_too_short',
79
+ // ── 跨设备同步(2.27.0)──
80
+ no_host: 'no_host',
81
+ no_remote_path: 'no_remote_path',
82
+ sync_failed: 'sync_failed',
79
83
  // ── 其它 ──
80
84
  memory_unavailable: 'memory_unavailable',
81
85
  flood: 'flood',
@@ -0,0 +1,89 @@
1
+ /**
2
+ * sync 层 —— **基线**(IO)。`<状态根>/sync/base.json`,只在本机、不同步。
3
+ *
4
+ * 基线是三张表里唯一「不是从磁盘现状读出来的」那张:它记的是**上次检查时两边长什么样**。
5
+ * 没有它,就只能两边硬比 —— 分不清「我改的」和「本来就不一样」。
6
+ *
7
+ * 三条纪律:
8
+ * 1. **每台机器各一份**。它不进记忆目录、不进 mirror、不进 intake,天然不需要共享。
9
+ * 2. **只有显式要求才写**。`check.js` 默认不落盘 —— 第 1 步的承诺是「一个字节都不写」,
10
+ * 基线是唯一例外,且必须由调用方点名。
11
+ * 3. **坏基线当没有基线**。读到坏 JSON 就当首次同步(最坏后果是多看几行「新增」),
12
+ * 绝不因为基线坏了而拒绝出报告。
13
+ */
14
+ import { mkdir, readFile } from 'node:fs/promises'
15
+ import { join } from 'node:path'
16
+ import { writeFileAtomic } from '../memory/util.js'
17
+
18
+ /** 基线格式版本。改了结构要 +1,旧版会被当成「没有基线」。 */
19
+ export const BASE_VERSION = 1
20
+
21
+ /**
22
+ * @param {string} stateRoot
23
+ * @returns {string} `base.json` 的绝对路径
24
+ */
25
+ export function basePathOf(stateRoot) {
26
+ return join(stateRoot, 'sync', 'base.json')
27
+ }
28
+
29
+ /**
30
+ * 读基线。没有 / 坏了 / 版本不对 → 都返回 `null`(调用方按首次同步处理)。
31
+ *
32
+ * @param {string} stateRoot
33
+ * @returns {Promise<{version:number, at:string|null, host:string|null, remotePath:string|null, files:Map<string,string>}|null>}
34
+ */
35
+ export async function readBase(stateRoot) {
36
+ let raw
37
+ try {
38
+ raw = await readFile(basePathOf(stateRoot), 'utf8')
39
+ } catch {
40
+ return null
41
+ }
42
+ let parsed
43
+ try {
44
+ parsed = JSON.parse(raw)
45
+ } catch {
46
+ return null
47
+ }
48
+ if (!parsed || typeof parsed !== 'object') return null
49
+ if (parsed.version !== BASE_VERSION) return null
50
+ const filesRaw = parsed.files && typeof parsed.files === 'object' ? parsed.files : {}
51
+ const files = new Map()
52
+ for (const [name, sha] of Object.entries(filesRaw)) {
53
+ if (typeof name === 'string' && typeof sha === 'string' && sha !== '') files.set(name, sha)
54
+ }
55
+ return {
56
+ version: BASE_VERSION,
57
+ at: typeof parsed.at === 'string' ? parsed.at : null,
58
+ host: typeof parsed.host === 'string' ? parsed.host : null,
59
+ remotePath: typeof parsed.remotePath === 'string' ? parsed.remotePath : null,
60
+ files,
61
+ }
62
+ }
63
+
64
+ /**
65
+ * 写基线(**只在 `updateBase: true` 时由 `check.js` 调用**)。
66
+ *
67
+ * 写的是「这一次检查看到的**远端**清单」—— 基线的语义是「上次同步确认过的远端状态」。
68
+ * 用本地清单当基线会把本地刚改的东西记成「已同步」,下次就再也报不出来了。
69
+ *
70
+ * @param {string} stateRoot
71
+ * @param {object} input
72
+ * @param {Map<string,string>} input.files — 远端清单
73
+ * @param {string} input.host
74
+ * @param {string} input.remotePath
75
+ * @param {string} [input.at] — ISO 时间
76
+ */
77
+ export async function writeBase(stateRoot, { files, host, remotePath, at }) {
78
+ const dir = join(stateRoot, 'sync')
79
+ await mkdir(dir, { recursive: true })
80
+ const payload = {
81
+ version: BASE_VERSION,
82
+ at: at ?? new Date().toISOString(),
83
+ host: String(host ?? ''),
84
+ remotePath: String(remotePath ?? ''),
85
+ files: Object.fromEntries([...files.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))),
86
+ }
87
+ await writeFileAtomic(basePathOf(stateRoot), `${JSON.stringify(payload, null, 2)}\n`)
88
+ return payload
89
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * sync 层 —— **wiring**(把三张表凑齐、跑比对、出报告)。
3
+ *
4
+ * 这里只做顺序与错误处理,**不含任何判据**:分类在 `policy.js`,
5
+ * sha 在 `manifest.js` / `remote.js`,基线在 `base.js`。
6
+ *
7
+ * 顺序是有意为之:**先拉远端**。远端不可达就立刻抛错,此时本地清单还没算、
8
+ * 基线还没读、报告还没生成 —— 「不产生任何半成品状态」这条判据靠顺序保证,
9
+ * 不靠事后清理。
10
+ *
11
+ * 2.27.0 的硬承诺:**记忆目录一个字节都不写**。本文件里除了可选的 `writeBase`
12
+ * (写的是状态根下的基线,不是记忆目录)没有任何写操作。
13
+ */
14
+ import { readBase, writeBase } from './base.js'
15
+ import { localManifest } from './manifest.js'
16
+ import { classifySync, diffCount, parseRemoteManifest, renderSyncReport } from './policy.js'
17
+ import { fetchRemoteManifest } from './remote.js'
18
+
19
+ /**
20
+ * 跑一次只读跨设备检查。
21
+ *
22
+ * @param {object} input
23
+ * @param {string} input.memoryDir — 记忆目录(读)
24
+ * @param {string} input.stateRoot — 状态根(基线落这里)
25
+ * @param {string} input.host — ssh 主机别名
26
+ * @param {string} input.remotePath — 远端记忆目录
27
+ * @param {boolean} [input.updateBase] — 显式要求才把本次远端清单记成新基线
28
+ * @param {number} [input.now] — 时间戳(测试可注入)
29
+ * @param {object} [input.deps] — 注入点,测试用来替掉 ssh / 磁盘
30
+ * @returns {Promise<object>}
31
+ */
32
+ export async function runSyncCheck({
33
+ memoryDir,
34
+ stateRoot,
35
+ host,
36
+ remotePath,
37
+ updateBase = false,
38
+ now = Date.now(),
39
+ deps = {},
40
+ }) {
41
+ const remoteFetch =
42
+ deps.fetchRemoteManifest ?? ((args) => fetchRemoteManifest({ ...args, run: deps.remoteRun }))
43
+ const localScan = deps.localManifest ?? localManifest
44
+ const baseRead = deps.readBase ?? readBase
45
+ const baseWrite = deps.writeBase ?? writeBase
46
+
47
+ const at = new Date(now).toISOString()
48
+
49
+ // ① 远端先来:不可达就在这里失败,后面一步都还没发生
50
+ const raw = await remoteFetch({ host, remotePath })
51
+ const { files: remoteFiles, skipped: skippedRemote } = parseRemoteManifest(raw?.stdout ?? '')
52
+
53
+ // ② 本地清单
54
+ const { files: localFiles, skipped: skippedLocal } = await localScan(memoryDir)
55
+
56
+ // ③ 基线。存的是**另一个远端**的基线时按「没有基线」处理 ——
57
+ // 拿 A 机器的基线去判 B 机器,会把两边的独立改动全判成「两侧都改」。
58
+ const stored = await baseRead(stateRoot)
59
+ const usable = stored && (!stored.host || stored.host === host) && (!stored.remotePath || stored.remotePath === remotePath)
60
+ const baseFiles = usable ? stored.files : null
61
+ const hasBase = baseFiles !== null
62
+
63
+ // ④ 三方比对
64
+ const result = classifySync({ local: localFiles, remote: remoteFiles, base: baseFiles })
65
+
66
+ // ⑤ 报告
67
+ const report = renderSyncReport({
68
+ result,
69
+ host,
70
+ remotePath,
71
+ at,
72
+ hasBase,
73
+ skippedRemote,
74
+ skippedLocal,
75
+ })
76
+
77
+ // ⑥ 基线(显式要求才写;写的是远端清单,不是本地 —— 见 base.js 的说明)
78
+ let baseUpdated = false
79
+ if (updateBase) {
80
+ await baseWrite(stateRoot, { files: remoteFiles, host, remotePath, at })
81
+ baseUpdated = true
82
+ }
83
+
84
+ return {
85
+ ok: true,
86
+ at,
87
+ host,
88
+ remotePath,
89
+ hasBase,
90
+ baseUpdated,
91
+ skippedRemote,
92
+ skippedLocal,
93
+ localCount: localFiles.size,
94
+ remoteCount: remoteFiles.size,
95
+ baseCount: baseFiles ? baseFiles.size : 0,
96
+ diff: diffCount(result),
97
+ counts: result.counts,
98
+ result,
99
+ report,
100
+ }
101
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * sync 层 —— **本地清单**(IO)。只读记忆目录、只算哈希,**不写任何东西**。
3
+ *
4
+ * 范围与 sage-mem 自己「眼里的记忆」保持一致:走 `isMemoryEntry()` 同一道闸门
5
+ * (`.md` + 非保留目录项 + 非冲突副本)。好处是两边口径不会分叉 ——
6
+ * 同步报告里出现的文件名,一定也是检索/注入能看见的那些。
7
+ *
8
+ * 为什么不复用 `scanMemoryDirDetailed()`:那个带缓存与代次判断,为「每轮注入都要跑」
9
+ * 设计;这里是一次性命令,缓存只会让第二次检查读到过期结果。
10
+ */
11
+ import { createHash } from 'node:crypto'
12
+ import { readdir, readFile } from 'node:fs/promises'
13
+ import { join } from 'node:path'
14
+ import { isMemoryEntry } from '../memory/naming.js'
15
+
16
+ /**
17
+ * 扫一遍记忆目录,返回 `文件名 → sha256`。
18
+ *
19
+ * @param {string} memoryDir
20
+ * @returns {Promise<{files: Map<string,string>, skipped: number}>}
21
+ */
22
+ export async function localManifest(memoryDir) {
23
+ let names
24
+ try {
25
+ names = await readdir(memoryDir)
26
+ } catch (err) {
27
+ const code = err?.code ?? 'unknown'
28
+ throw new Error(`读不到记忆目录(${code}):${memoryDir}`)
29
+ }
30
+
31
+ const files = new Map()
32
+ let skipped = 0
33
+
34
+ for (const name of names.sort()) {
35
+ if (!isMemoryEntry(name)) {
36
+ skipped += 1
37
+ continue
38
+ }
39
+ let buf
40
+ try {
41
+ buf = await readFile(join(memoryDir, name))
42
+ } catch {
43
+ // 单个文件读失败(权限、正在被写、链接断了)不该让整次检查失败 ——
44
+ // 记成跳过,报告抬头会写出来。
45
+ skipped += 1
46
+ continue
47
+ }
48
+ files.set(name, createHash('sha256').update(buf).digest('hex'))
49
+ }
50
+
51
+ return { files, skipped }
52
+ }
@@ -0,0 +1,398 @@
1
+ /**
2
+ * sync 层 —— **纯逻辑**:三方比对分类器、清单解析、报告渲染(2.27.0)。
3
+ *
4
+ * 三层分工(见 `docs/2.27.0-plan.md`):
5
+ * - 这里只有纯函数,**不 import 任何 `node:` 模块**,不起进程、不碰磁盘。
6
+ * - 拿不到磁盘的家伙(`manifest.js` / `base.js` / `remote.js`)负责把三个 Map 凑齐。
7
+ * - 分类与措辞的**唯一真相在这里**:别在 wiring 里另写一套判断。
8
+ *
9
+ * 为什么三方比对而不是两边比:只有「基线」能区分「我改的」与「本来就不一样」。
10
+ * 基线是**每台机器各一份**的本地状态(`base.json`),天然不需要共享。
11
+ *
12
+ * 判据来源:本机《跨设备同步:决策级调研》(2026-11-24,不随仓库发布)§6 第 1 步。
13
+ * 那一步的硬约束是**一个字节都不写** —— 本模块连写函数都没有。
14
+ */
15
+
16
+ /**
17
+ * 一个文件在本次比对里的去向。
18
+ *
19
+ * 前 6 类对应报告 §6 第 1 步点名的四类(`remote-new` / `remote-changed` /
20
+ * `local-changed` / `both-changed`),后 5 类是三态组合里剩下的现实情况 ——
21
+ * 报告没点名不等于不会发生,**漏分类会让「未分类」静默消失**。
22
+ */
23
+ export const SYNC_CLASSES = [
24
+ 'same',
25
+ 'remote-new',
26
+ 'local-new',
27
+ 'remote-changed',
28
+ 'local-changed',
29
+ 'both-changed',
30
+ 'both-new-diverged',
31
+ 'local-deleted-remote-changed',
32
+ 'local-changed-remote-deleted',
33
+ 'remote-deleted',
34
+ 'local-deleted',
35
+ 'inconsistent',
36
+ ]
37
+
38
+ /** 需要人来裁决的类别(`same` 之外的差异里,这几类不能自动处理)。 */
39
+ export const CONFLICT_CLASSES = new Set([
40
+ 'both-changed',
41
+ 'both-new-diverged',
42
+ 'local-deleted-remote-changed',
43
+ 'local-changed-remote-deleted',
44
+ ])
45
+
46
+ /** 会改变记忆目录内容的类别(2.27.0 只报告、不执行,`check.js` 据此打警告)。 */
47
+ export const ACTIONABLE_CLASSES = new Set([
48
+ 'remote-new',
49
+ 'local-new',
50
+ 'remote-changed',
51
+ 'local-changed',
52
+ ...CONFLICT_CLASSES,
53
+ 'remote-deleted',
54
+ 'local-deleted',
55
+ ])
56
+
57
+ /**
58
+ * 一个位置的状态。
59
+ *
60
+ * `absent` 与 `new` 的区别:后者「有内容但没有基线」,不是「新增过」——
61
+ * 首次同步时所有文件都是 `new`,这是正常的,不该刷成一片「两侧都改」。
62
+ *
63
+ * @param {string|undefined} value — 本次看到的 sha256
64
+ * @param {string|undefined} base — 基线里的 sha256
65
+ * @returns {'absent'|'new'|'same'|'changed'}
66
+ */
67
+ export function stateOf(value, base) {
68
+ if (value === undefined || value === null || value === '') return 'absent'
69
+ if (base === undefined || base === null || base === '') return 'new'
70
+ return value === base ? 'same' : 'changed'
71
+ }
72
+
73
+ /**
74
+ * 三态 → 类别。纯查表,不含任何 IO。
75
+ *
76
+ * 表里出现 `inconsistent` 的组合是逻辑上矛盾的(例如「本地等于基线」+「远端没有基线」),
77
+ * 真出现说明三个 Map 来源不一致 —— **宁可报出来,不要静默归进某一类**。
78
+ *
79
+ * @param {string} localSha
80
+ * @param {string} remoteSha
81
+ * @param {string} baseSha
82
+ * @returns {string} 见 `SYNC_CLASSES`
83
+ */
84
+ export function classifyOne(localSha, remoteSha, baseSha) {
85
+ const L = stateOf(localSha, baseSha)
86
+ const R = stateOf(remoteSha, baseSha)
87
+
88
+ if (L === 'same' && R === 'same') return 'same'
89
+ // 两边都没有、基线里有 = 两份都删了。对同步而言这是**一致**,
90
+ // 不该因为「基线还记得它」就报成一个待处理差异。
91
+ if (L === 'absent' && R === 'absent') return 'same'
92
+ if (L === 'same' && R === 'absent') return 'remote-deleted'
93
+ if (L === 'absent' && R === 'same') return 'local-deleted'
94
+ if (L === 'same' && R === 'changed') return 'remote-changed'
95
+ if (L === 'changed' && R === 'same') return 'local-changed'
96
+ if (L === 'changed' && R === 'changed') return 'both-changed'
97
+ if (L === 'absent' && R === 'new') return 'remote-new'
98
+ if (L === 'new' && R === 'absent') return 'local-new'
99
+ if (L === 'absent' && R === 'changed') return 'local-deleted-remote-changed'
100
+ if (L === 'changed' && R === 'absent') return 'local-changed-remote-deleted'
101
+
102
+ // 两侧都没有基线:两边各自新增。内容一致就当没差异(同一份记忆副本),
103
+ // 不一致才是真歧义 —— 这正是「首次同步」最常见的形态。
104
+ if (L === 'new' && R === 'new') return localSha === remoteSha ? 'same' : 'both-new-diverged'
105
+
106
+ return 'inconsistent'
107
+ }
108
+
109
+ /** Map 取值,允许传普通对象(测试里手写更省事)。 */
110
+ function lookup(map, key) {
111
+ if (!map) return undefined
112
+ if (map instanceof Map) return map.get(key)
113
+ return Object.prototype.hasOwnProperty.call(map, key) ? map[key] : undefined
114
+ }
115
+
116
+ /**
117
+ * 三方比对。输入三张「文件名 → sha256」的表,输出逐文件结论。
118
+ *
119
+ * 名字集合取三张表的**并集** —— 只在基线和远端里有的文件(本地已删)也必须出现在结果里,
120
+ * 只扫本地会看不见「远端把我删掉的东西改了」这类情况。
121
+ *
122
+ * @param {object} input
123
+ * @param {Map<string,string>|object} input.local
124
+ * @param {Map<string,string>|object} input.remote
125
+ * @param {Map<string,string>|object} [input.base] — 缺省当空基线(首次同步)
126
+ * @returns {{entries: Array<{name:string, class:string, local?:string, remote?:string, base?:string}>, counts: Record<string,number>, names: string[]}}
127
+ */
128
+ export function classifySync({ local, remote, base } = {}) {
129
+ const names = new Set([...keysOf(local), ...keysOf(remote), ...keysOf(base)])
130
+ const sorted = [...names].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
131
+
132
+ const entries = []
133
+ const counts = {}
134
+ for (const c of SYNC_CLASSES) counts[c] = 0
135
+
136
+ for (const name of sorted) {
137
+ const localSha = lookup(local, name)
138
+ const remoteSha = lookup(remote, name)
139
+ const baseSha = lookup(base, name)
140
+ const cls = classifyOne(localSha, remoteSha, baseSha)
141
+ counts[cls] = (counts[cls] ?? 0) + 1
142
+ entries.push({ name, class: cls, local: localSha, remote: remoteSha, base: baseSha })
143
+ }
144
+
145
+ return { entries, counts, names: sorted }
146
+ }
147
+
148
+ /** Map 或对象的键,统一成数组。 */
149
+ function keysOf(map) {
150
+ if (!map) return []
151
+ if (map instanceof Map) return [...map.keys()]
152
+ return Object.keys(map)
153
+ }
154
+
155
+ /** 有差异的条目(`same` 之外的全部),按类别分组、组内按名字排序。 */
156
+ export function groupByClass(result) {
157
+ const out = new Map()
158
+ for (const c of SYNC_CLASSES) out.set(c, [])
159
+ for (const e of result?.entries ?? []) {
160
+ if (e.class === 'same') continue
161
+ out.get(e.class).push(e.name)
162
+ }
163
+ for (const list of out.values()) list.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
164
+ return out
165
+ }
166
+
167
+ /** 有差异的条目总数(不含 `same`)。 */
168
+ export function diffCount(result) {
169
+ return (result?.entries ?? []).filter((e) => e.class !== 'same').length
170
+ }
171
+
172
+ /** 需要人裁决的条目。 */
173
+ export function conflicts(result) {
174
+ return (result?.entries ?? []).filter((e) => CONFLICT_CLASSES.has(e.class))
175
+ }
176
+
177
+ /**
178
+ * 名字是否可接受:必须是一个 `.md` 基名。
179
+ *
180
+ * 不接受任何路径分隔符与 `..` —— 远端清单是**外部输入**,
181
+ * 一个含 `../` 的名字就足够让后续步骤写到记忆目录之外。
182
+ *
183
+ * @param {string} name
184
+ */
185
+ export function isSafeSyncName(name) {
186
+ if (typeof name !== 'string') return false
187
+ const n = name.trim()
188
+ if (n === '' || n.length > 200) return false
189
+ if (n.includes('/') || n.includes('\\') || n.includes('\0')) return false
190
+ if (n === '.' || n === '..') return false
191
+ if (!n.toLowerCase().endsWith('.md')) return false
192
+ return true
193
+ }
194
+
195
+ /**
196
+ * 解析 `sha256sum` 的输出(`<hex> <path>` 每行一条)成 `名字 → sha256`。
197
+ *
198
+ * 容忍三件事:前后空行、`./` 前缀、路径里的空格(`sha256sum` 用两个空格分隔,
199
+ * 所以要在**前 64 位之后的第一个双空格**处切,不能 `split(/\s+/)`)。
200
+ *
201
+ * 不安全或非 `.md` 的名字**直接丢掉并计数**,不抛错 —— 远端可能有编辑器备份
202
+ * (`x.md~`)、隐藏文件、子目录产物,它们不该让整次同步失败。
203
+ *
204
+ * @param {string} text
205
+ * @returns {{files: Map<string,string>, skipped: number}}
206
+ */
207
+ export function parseRemoteManifest(text) {
208
+ const files = new Map()
209
+ let skipped = 0
210
+ for (const rawLine of String(text ?? '').split(/\r?\n/)) {
211
+ const line = rawLine.trim()
212
+ if (line === '') continue
213
+ const m = /^([0-9a-f]{64})\s+(.+)$/i.exec(line)
214
+ if (!m) {
215
+ skipped += 1
216
+ continue
217
+ }
218
+ const sha = m[1].toLowerCase()
219
+ let path = m[2].trim()
220
+ // `tar`/`find` 有时给 `./名字`,统一去前缀
221
+ while (path.startsWith('./')) path = path.slice(2)
222
+ // 只认记忆目录**根**下的文件:子目录里的不算这次同步范围
223
+ if (path.includes('/') || path.includes('\\')) {
224
+ skipped += 1
225
+ continue
226
+ }
227
+ if (!isSafeSyncName(path)) {
228
+ skipped += 1
229
+ continue
230
+ }
231
+ files.set(path, sha)
232
+ }
233
+ return { files, skipped }
234
+ }
235
+
236
+ /** 类别的中文短名(报告与面板共用一处,别各写各的)。 */
237
+ export const CLASS_LABEL = {
238
+ same: '一致',
239
+ 'remote-new': '远端新增',
240
+ 'local-new': '本地新增',
241
+ 'remote-changed': '仅远端改',
242
+ 'local-changed': '仅本地改',
243
+ 'both-changed': '两侧都改',
244
+ 'both-new-diverged': '两侧各自新增且内容不同',
245
+ 'local-deleted-remote-changed': '本地已删、远端改过',
246
+ 'local-changed-remote-deleted': '本地改过、远端已删',
247
+ 'remote-deleted': '远端已删',
248
+ 'local-deleted': '本地已删',
249
+ inconsistent: '数据不一致(三张表对不上)',
250
+ }
251
+
252
+ /**
253
+ * 渲染成 markdown 报告。
254
+ *
255
+ * 措辞纪律:**只陈述看见的事实,不给建议**。这一步不执行任何动作,
256
+ * 写「建议合并」会让人以为插件要替它做决定。
257
+ *
258
+ * @param {object} input
259
+ * @param {object} input.result — `classifySync()` 的返回值
260
+ * @param {string} input.host
261
+ * @param {string} input.remotePath
262
+ * @param {string} [input.at] — ISO 时间
263
+ * @param {boolean} [input.hasBase] — 之前有没有基线(决定首次同步的措辞)
264
+ * @param {number} [input.skippedRemote] — 远端被跳过的条目数
265
+ * @param {number} [input.skippedLocal] — 本地被跳过的条目数
266
+ * @returns {string}
267
+ */
268
+ export function renderSyncReport({ result, host, remotePath, at, hasBase, skippedRemote = 0, skippedLocal = 0 }) {
269
+ const counts = result?.counts ?? {}
270
+ const diff = diffCount(result)
271
+ const risky = conflicts(result)
272
+ const lines = []
273
+
274
+ lines.push('# 跨设备同步 · 只读差异报告(2.27.0)')
275
+ lines.push('')
276
+ lines.push(`- 远端:\`${host}\` 的 \`${remotePath}\``)
277
+ if (at) lines.push(`- 生成时间:${at}`)
278
+ lines.push(`- 基线:${hasBase ? '有(上次同步的哈希表)' : '**无 —— 本次是首次同步,所有文件都按「新增」看**'}`)
279
+ lines.push(`- 扫描:本地 ${countOf(result, 'local')} 个文件,已跳过 ${skippedLocal} 个;远端清单跳过 ${skippedRemote} 条`)
280
+ lines.push('')
281
+
282
+ if (diff === 0) {
283
+ lines.push('**两侧完全一致,没有需要处理的差异。**')
284
+ if (skippedRemote > 0 || skippedLocal > 0) {
285
+ lines.push('')
286
+ lines.push('> 注意:有被跳过的条目(非 `.md`、在子目录里、或名字不安全)。它们不在比对范围内。')
287
+ }
288
+ lines.push('')
289
+ lines.push('> 这是只读检查。本次运行没有修改记忆目录里的任何文件。')
290
+ return `${lines.join('\n')}\n`
291
+ }
292
+
293
+ lines.push(`共 **${diff}** 个文件有差异${risky.length > 0 ? `,其中 **${risky.length}** 个需要人来裁决` : ''}。`)
294
+ lines.push('')
295
+ lines.push('| 类别 | 数量 |')
296
+ lines.push('|---|---|')
297
+
298
+ const groups = groupByClass(result)
299
+ for (const c of SYNC_CLASSES) {
300
+ const n = groups.get(c)?.length ?? 0
301
+ if (n === 0) continue
302
+ const mark = CONFLICT_CLASSES.has(c) ? ' ⚠️' : ''
303
+ lines.push(`| ${CLASS_LABEL[c] ?? c}${mark} | ${n} |`)
304
+ }
305
+ lines.push('')
306
+
307
+ for (const c of SYNC_CLASSES) {
308
+ const names = groups.get(c) ?? []
309
+ if (names.length === 0) continue
310
+ lines.push(`## ${CLASS_LABEL[c] ?? c}(${names.length})`)
311
+ lines.push('')
312
+ for (const name of names) lines.push(`- \`${name}\``)
313
+ lines.push('')
314
+ }
315
+
316
+ if (risky.length > 0) {
317
+ lines.push('---')
318
+ lines.push('')
319
+ lines.push('> ⚠️ 标了 ⚠️ 的类别**不能自动处理**:两侧都动过同一个文件时,「谁赢」是人的决定,')
320
+ lines.push('> 不是插件的决定。2.27.0 只出这份报告,一个字节都不写。')
321
+ lines.push('')
322
+ }
323
+
324
+ lines.push('> 这是只读检查。本次运行没有修改记忆目录里的任何文件。')
325
+ return `${lines.join('\n')}\n`
326
+ }
327
+
328
+ /** 统计某一边的有效条目数(报告抬头用)。 */
329
+ function countOf(result, side) {
330
+ let n = 0
331
+ for (const e of result?.entries ?? []) {
332
+ if (e[side] !== undefined && e[side] !== null && e[side] !== '') n += 1
333
+ }
334
+ return n
335
+ }
336
+
337
+ // ── 设置面(与 `mirror/policy.js` 的 resolveExternal / parseExternalPatch 对称)──
338
+ //
339
+ // 为什么放在 policy 里而不是 settings.js:**校验判据只有一份**。
340
+ // settings.js 负责读写文件,判「什么样的远端名算合法」由这里说了算。
341
+
342
+ /** 缺省同步设置:host 为空 = 没配,工具会明确拒绝而不是瞎猜一个远端。 */
343
+ export const DEFAULT_SYNC = { host: '', remotePath: '' }
344
+
345
+ /**
346
+ * 把设置文件里那一段解析成生效值,顺带给出诊断。
347
+ *
348
+ * 坏值**不抛错**:把非法的那个字段清空并写进 `diagnostics`,
349
+ * 让其余配置照常生效 —— 一个手滑的空格不该让整个同步功能消失。
350
+ *
351
+ * @param {unknown} raw — 设置文件里的 `sync` 段(任意值)
352
+ * @returns {{sync: {host: string, remotePath: string}, diagnostics: string[]}}
353
+ */
354
+ export function resolveSync(raw) {
355
+ const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
356
+ const diagnostics = []
357
+
358
+ let host = typeof input.host === 'string' ? input.host.trim() : ''
359
+ let remotePath = typeof input.remotePath === 'string' ? input.remotePath.trim() : ''
360
+
361
+ if (host !== '' && /\s|[\0\n\r]/.test(host)) {
362
+ diagnostics.push('远端主机名不能含空白或控制字符,已忽略')
363
+ host = ''
364
+ }
365
+ if (remotePath !== '' && /[\0\n\r]/.test(remotePath)) {
366
+ diagnostics.push('远端记忆目录不能含控制字符,已忽略')
367
+ remotePath = ''
368
+ }
369
+
370
+ return { sync: { host, remotePath }, diagnostics }
371
+ }
372
+
373
+ /**
374
+ * 面板/工具传来的补丁。与 `parseExternalPatch` 同一个返回形状(`{ok, patch}`),
375
+ * 理由也一样:**绝不静默丢掉不认识的键** —— 手滑写错一个字段名却「保存成功」,
376
+ * 比直接报错难受得多。
377
+ *
378
+ * @param {unknown} raw
379
+ * @returns {{ok: boolean, patch?: object|null, error?: string}}
380
+ */
381
+ export function parseSyncPatch(raw) {
382
+ if (raw === undefined || raw === null) return { ok: true, patch: null }
383
+ if (typeof raw !== 'object' || Array.isArray(raw)) return { ok: false, error: 'sync 必须是一个对象' }
384
+ const allowed = new Set(['host', 'remotePath'])
385
+ for (const key of Object.keys(raw)) {
386
+ if (!allowed.has(key)) return { ok: false, error: `sync 里不认识的键:${key}` }
387
+ }
388
+ const out = {}
389
+ if ('host' in raw) {
390
+ if (typeof raw.host !== 'string') return { ok: false, error: 'sync.host 必须是字符串' }
391
+ out.host = raw.host.trim()
392
+ }
393
+ if ('remotePath' in raw) {
394
+ if (typeof raw.remotePath !== 'string') return { ok: false, error: 'sync.remotePath 必须是字符串' }
395
+ out.remotePath = raw.remotePath.trim()
396
+ }
397
+ return { ok: true, patch: out }
398
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * sync 层 —— **远端清单**(IO)。整个 sync 模块里**唯一会起子进程的地方**。
3
+ *
4
+ * 为什么是 ssh 而不是自研传输:2026-11-24 的决策级调研(§5.1 / §5.3)实测过本机现状 ——
5
+ * `ssh` / `scp` / `tar` 都在,`rsync` 缺失,`~/.ssh/config` 里已有主机条目。
6
+ * 传输零新增配置、零常驻进程,符合 D34「不引入第二个进程」。
7
+ *
8
+ * 为什么只拉清单不拉内容:2.27.0 的承诺是「一个字节都不写」。
9
+ * 清单本身就是 130 个文件 × 72 字节 ≈ 10 KB,比整份记忆(1.36 MB)小两个数量级。
10
+ *
11
+ * 安全:`remotePath` 来自设置(人填的),但仍然是**要进远端 shell 的字符串** ——
12
+ * 一律单引号包裹并转义内部单引号,拒绝换行与控制字符。主机名同样不拼进命令。
13
+ */
14
+ import { execFile } from 'node:child_process'
15
+
16
+ /** ssh 默认超时。跨公网也够,卡住时宁可报错也不要挂着。 */
17
+ export const DEFAULT_TIMEOUT_MS = 20000
18
+
19
+ /** 单次清单输出的上限。130 个文件约 10 KB,给 4 MB 是「绝不可能撞上」的量级。 */
20
+ const MAX_BUFFER = 4 * 1024 * 1024
21
+
22
+ /**
23
+ * 生成在**远端**执行的命令。
24
+ *
25
+ * `-exec sha256sum {} +` 比 `-exec ... \;` 少起 N-1 个进程;
26
+ * `-maxdepth 1` 把子目录排除在外(与本地 `readdir` 的口径一致)。
27
+ *
28
+ * @param {string} remotePath — 远端记忆目录(绝对路径或 `~` 开头)
29
+ * @returns {string}
30
+ */
31
+ export function buildRemoteCommand(remotePath) {
32
+ const p = String(remotePath ?? '').trim()
33
+ if (p === '') throw new Error('未配置远端记忆目录')
34
+ if (/[\0\n\r]/.test(p)) throw new Error('远端记忆目录含控制字符,拒绝执行')
35
+ const quoted = `'${p.replace(/'/g, `'\\''`)}'`
36
+ return `cd ${quoted} && find . -maxdepth 1 -type f -name '*.md' -exec sha256sum {} +`
37
+ }
38
+
39
+ /**
40
+ * 跑一次 ssh,拿回 `sha256sum` 的原始输出。
41
+ *
42
+ * 失败一律**抛错**,不返回半成品 —— 报告的第 3 条验收判据是
43
+ * 「远端不可达时明确报错退出,不产生任何半成品状态」。
44
+ *
45
+ * @param {object} input
46
+ * @param {string} input.host — `~/.ssh/config` 里的主机别名
47
+ * @param {string} input.remotePath
48
+ * @param {number} [input.timeoutMs]
49
+ * @param {Function} [input.run] — 注入点(测试用假执行器替换真 ssh)
50
+ * @returns {Promise<{stdout: string, stderr: string}>}
51
+ */
52
+ export async function fetchRemoteManifest({ host, remotePath, timeoutMs = DEFAULT_TIMEOUT_MS, run = defaultRun }) {
53
+ const h = String(host ?? '').trim()
54
+ if (h === '') throw new Error('未配置远端主机(SSH 别名)')
55
+ if (/\s|[\0\n\r]/.test(h)) throw new Error('远端主机名不合法(含空白或控制字符)')
56
+
57
+ const command = buildRemoteCommand(remotePath)
58
+
59
+ let out
60
+ try {
61
+ out = await run({ host: h, command, timeoutMs })
62
+ } catch (err) {
63
+ const reason = err?.timedOut
64
+ ? `超时(${timeoutMs} ms)`
65
+ : String(err?.stderr ?? '').trim() || String(err?.message ?? err)
66
+ throw new Error(`连不上远端 \`${h}\`:${reason}`)
67
+ }
68
+
69
+ const stdout = String(out?.stdout ?? '')
70
+ const stderr = String(out?.stderr ?? '').trim()
71
+ // `cd` 失败时 find 会静默输出空 —— 空输出 + 非空 stderr 一律当错误,
72
+ // 否则「远端目录填错了」会被读成「远端一条记忆都没有」,然后本地全部显示为「远端已删」。
73
+ if (stdout.trim() === '' && stderr !== '') {
74
+ throw new Error(`远端执行失败:${stderr}`)
75
+ }
76
+ return { stdout, stderr }
77
+ }
78
+
79
+ /**
80
+ * 真正调 ssh。抽成独立函数是为了让测试能整条绕开(`run` 注入点)。
81
+ *
82
+ * @param {{host: string, command: string, timeoutMs: number}} input
83
+ * @returns {Promise<{stdout: string, stderr: string}>}
84
+ */
85
+ function defaultRun({ host, command, timeoutMs }) {
86
+ return new Promise((resolve, reject) => {
87
+ execFile(
88
+ 'ssh',
89
+ [
90
+ '-o', 'BatchMode=yes', // 绝不弹交互式密码提示:拿不到密钥就直接失败
91
+ '-o', 'ConnectTimeout=10',
92
+ host,
93
+ command,
94
+ ],
95
+ { timeout: timeoutMs, maxBuffer: MAX_BUFFER, windowsHide: true },
96
+ (err, stdout, stderr) => {
97
+ if (err) {
98
+ const e = new Error(err.message)
99
+ e.stderr = stderr
100
+ e.timedOut = err.killed === true || err.signal === 'SIGTERM'
101
+ e.code = err.code
102
+ reject(e)
103
+ return
104
+ }
105
+ resolve({ stdout, stderr })
106
+ },
107
+ )
108
+ })
109
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * sage-mem —— `memory_sync_check`(2.27.0 跨设备只读检查)。
3
+ *
4
+ * 定位:**这是「看清楚」,不是「动手」**。它跑完只产出一份报告,
5
+ * 记忆目录一个字节都不碰 —— 这条承诺由 `sync/check.js` 的顺序保证(先拉远端,
6
+ * 失败就止步),这里只负责把参数收齐、把错误翻成人话。
7
+ *
8
+ * 为什么单独成文件而不并进 `memory-tools.js`:那个文件已经是「检索三件套」的家
9
+ * (428 行),同步是完全不相干的一件事 —— 并进去只会让它继续长。
10
+ *
11
+ * 失败是值,不是异常(与检索工具同一条纪律):连不上远端不该打断模型那一轮。
12
+ */
13
+ import { join } from 'node:path'
14
+ import { MEMORY_DIR, STATE_ROOT } from '../memory/config.js'
15
+ import { runSyncCheck } from '../sync/check.js'
16
+ import { DEFAULT_SYNC, resolveSync } from '../sync/policy.js'
17
+
18
+ const text = (s) => [{ type: 'text', text: String(s ?? '') }]
19
+
20
+ /**
21
+ * @param {object} input
22
+ * @param {() => Promise<{sync: object}>} input.readSettings — 读当前生效设置(settings.js 提供)
23
+ * @param {object} [input.overrides] — 测试注入:`{ memoryDir, stateRoot, deps }`
24
+ */
25
+ export function createSyncTool({ readSettings, overrides = {} }) {
26
+ return {
27
+ name: 'memory_sync_check',
28
+ description:
29
+ '跨设备只读检查:把远端(ssh 主机)记忆目录的 sha256 清单,与本地清单、以及上次同步基线做三方比对,'
30
+ + '报出「远端新增 / 仅远端改 / 仅本地改 / 两侧都改」等差异。**只读,一个字节都不写记忆目录**。'
31
+ + '一侧动过、另一侧没动 = 可安全搬运;两侧都动过 = 需要人裁决,工具不会替你决定。'
32
+ + '主机与远端目录来自设置(外部访问 → 跨设备),也可以临时传参覆盖。',
33
+ parameters: {
34
+ type: 'object',
35
+ properties: {
36
+ host: {
37
+ type: 'string',
38
+ description: 'SSH 主机别名(~/.ssh/config 里的名字)。省略则用设置里的值。',
39
+ },
40
+ remotePath: {
41
+ type: 'string',
42
+ description: '远端记忆目录的绝对路径。省略则用设置里的值。',
43
+ },
44
+ updateBase: {
45
+ type: 'boolean',
46
+ description:
47
+ '把本次看到的远端清单记为新的基线。默认 false。'
48
+ + '只在「你已经把差异处理完、两边的现状就是你要的基线」时才该传 true。',
49
+ },
50
+ },
51
+ required: [],
52
+ additionalProperties: false,
53
+ },
54
+ async execute(args = {}) {
55
+ try {
56
+ const settings = await readSettings().catch(() => ({ sync: DEFAULT_SYNC }))
57
+ const resolved = resolveSync(settings?.sync)
58
+
59
+ const host = String(args.host ?? '').trim() || resolved.sync.host
60
+ const remotePath = String(args.remotePath ?? '').trim() || resolved.sync.remotePath
61
+
62
+ if (host === '') {
63
+ return {
64
+ ok: false,
65
+ code: 'no_host',
66
+ error: '错误:no_host — 还没配置远端主机。在「外部访问 → 跨设备」里填 SSH 别名,或这次直接传 host 参数。',
67
+ }
68
+ }
69
+ if (remotePath === '') {
70
+ return {
71
+ ok: false,
72
+ code: 'no_remote_path',
73
+ error: '错误:no_remote_path — 还没配置远端记忆目录。在设置里填,或这次直接传 remotePath 参数。',
74
+ }
75
+ }
76
+
77
+ const out = await runSyncCheck({
78
+ memoryDir: overrides.memoryDir ?? MEMORY_DIR,
79
+ stateRoot: overrides.stateRoot ?? STATE_ROOT,
80
+ host,
81
+ remotePath,
82
+ updateBase: args.updateBase === true,
83
+ deps: overrides.deps ?? {},
84
+ })
85
+
86
+ const note = out.baseUpdated
87
+ ? '\n> 已把本次的远端清单记为新的基线。\n'
88
+ : out.hasBase
89
+ ? ''
90
+ : '\n> 这次没有基线。确认差异无误后,用 `updateBase: true` 跑一次,之后就能分清「谁改的」。\n'
91
+
92
+ return {
93
+ ok: true,
94
+ ...pickNumbers(out),
95
+ content: text(`${out.report}${note}`),
96
+ }
97
+ } catch (err) {
98
+ const message = String(err?.message ?? err)
99
+ return {
100
+ ok: false,
101
+ code: 'sync_failed',
102
+ error: `错误:sync_failed — ${message}`,
103
+ }
104
+ }
105
+ },
106
+ }
107
+ }
108
+
109
+ /** 只把摘要字段带回去(`entries` 可能上百条,不该塞进工具返回值)。 */
110
+ function pickNumbers(out) {
111
+ return {
112
+ at: out.at,
113
+ host: out.host,
114
+ remotePath: out.remotePath,
115
+ hasBase: out.hasBase,
116
+ baseUpdated: out.baseUpdated,
117
+ diff: out.diff,
118
+ counts: out.counts,
119
+ localCount: out.localCount,
120
+ remoteCount: out.remoteCount,
121
+ }
122
+ }
123
+
124
+ /** 给 `assembly` 用的默认装配(真实磁盘 + 真实 ssh)。 */
125
+ export function defaultSyncPaths() {
126
+ return { memoryDir: MEMORY_DIR, stateRoot: join(STATE_ROOT) }
127
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "sage-mem",
3
3
  "description": "Cross-session memory for DeepSeek Harness — plain markdown files, no database, no worker.",
4
- "version": "2.26.0",
4
+ "version": "2.27.0",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "icon": "./icon.png",