sage-mem 2.33.4 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -35,9 +35,14 @@ import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
35
35
  import { mkdir, readFile, writeFile } from 'node:fs/promises'
36
36
  import { join } from 'node:path'
37
37
  import { checkUpdate as checkUpdateImpl } from './update.js'
38
- import { applySettingsPatch, MAX_RAW_BYTES, parseExperimentalPatch, parseUiPatch, pendingExperimental, pendingUi, rawName, readExternalSettings, readReservedFile, readSettingsFileDetailed, readSettingsSnapshot, RESERVED_FILE, SETTINGS_FILE } from './settings.js'
38
+ import { applySettingsPatch, MAX_RAW_BYTES, parseExperimentalPatch, parseUiPatch, pendingExperimental, pendingUi, rawName, readExternalSettings, readReservedFile, readSettingsFileDetailed, readSettingsSnapshot, readSyncSettings, RESERVED_FILE, SETTINGS_FILE } from './settings.js'
39
39
  import { createRecallInjector, createSessionInjectState, readRecallDebug } from './recall/index.js'
40
40
  import { mountAutodream, mountMemoryTools, mountMirror, mountObserve, mountPreCompact, mountWriteGate } from './assembly/index.js'
41
+ import { ensureLocalInstance } from './sync/instance.js'
42
+ import { listDevices } from './sync/devices.js'
43
+ import { runSyncAction } from './sync/panel.js'
44
+ // 3.0.0:跨设备冲突的裁决实现(`conflict/applyResolution` 背后的那一步)。
45
+ import { resolveSyncConflict } from './sync/resolve.js'
41
46
 
42
47
  /**
43
48
  * 读方法的拒绝:**抛**一个带 `.code` 的 Error(写方法返回 `{ok:false, code}` 回执,见 prepareWrite)。
@@ -49,6 +54,14 @@ import { mountAutodream, mountMemoryTools, mountMirror, mountObserve, mountPreCo
49
54
  function readReject(code, message) {
50
55
  return Object.assign(new Error(message), { code })
51
56
  }
57
+ /**
58
+ * 非空字符串才认(`code` / `error` 这类「有才带」的字段用它)。
59
+ * 单独起名字的另一个理由见 SyncGateway.run:直接写 `typeof x.code === 'string'`
60
+ * 会被错误码登记守卫当成「用了 `string` 这个业务码」。
61
+ */
62
+ function textOf(value) {
63
+ return typeof value === 'string' && value !== '' ? value : ''
64
+ }
52
65
  /**
53
66
  * 手动 @Remote marker 注册(Node 24 不解析装饰器语法,手写 decorator context)。
54
67
  */
@@ -73,7 +86,16 @@ export class MemoryGateway extends TypertRemoteService {
73
86
  // 2.0.0:冲突裁决入口(列表 / 读 / 标失效 / 驳回 / 撤销 / 删除记录)—— conflict.* 服务。
74
87
  // 与 memory / starmap 分开成独立 namespace:混成一个面会让「读记忆」与「改记忆的有效性」
75
88
  // 共用一张契约表,而后者是**写用户文件**的动作。
76
- new ConflictGateway(ctx)
89
+ //
90
+ // 3.0.0:把**本类的写盘能力**以函数形式交给它(`applyResolution` 的「留远端」要把正文写回本地)。
91
+ // 为什么走参数而不是在 ConflictGateway 里 `ctx.get('memory')`:此刻正在注册这个服务本身
92
+ // (与 tools-mount.js 头注同一条时序事实 —— 构造期读自己会拿到 undefined 或半成品)。
93
+ // 也不许在 lib/sync/ 里另写一份带 `expectedRevision` 的写盘:一条记忆的落盘口径只该有一处。
94
+ new ConflictGateway(ctx, (name, content, opts) => this.writeFile(name, content, opts))
95
+
96
+ // 3.1.0:跨设备同步的面板入口(设备候选 + 一次动作)—— `sync.*` 服务。
97
+ // 与 conflict 分开成独立 namespace:那边裁的是「本机两条记忆谁算数」,这边动的是网线与远端库。
98
+ new SyncGateway(ctx)
77
99
 
78
100
  // 四块挂载(1.2.0 从构造函数里搬出的四段)。顺序保持原样:
79
101
  // autodream → 检索工具 → 观测 → 写入门。
@@ -92,6 +114,12 @@ export class MemoryGateway extends TypertRemoteService {
92
114
  // 2.17.0:压缩前提醒(实验性,默认关;关着时每步只是一次开关读取)。
93
115
  mountPreCompact(ctx, { memoryDir: MEMORY_DIR })
94
116
 
117
+ // 3.0.0:本机设备身份(`<状态根>/instance.json`,只记 id / 机器名 / 创建时间)。
118
+ // **必须在装配期建好**:别的机器要推给我时,写入门第二道要能在我的状态根里读到它;
119
+ // 只在「我自己推送」时才创建,会让一台只收不推的机器永远收不到东西。
120
+ // 失败不阻断(只读盘 / 权限):后果只是别人推给我时要多确认一次,那是可接受的降级。
121
+ ensureLocalInstance(STATE_ROOT).catch(() => {})
122
+
95
123
  // 2.25.0:外部访问读侧(白名单导出 + 只读 MCP)。默认关,关着时一行都不跑。
96
124
  // `readExternal` 给的是**现读**设置(不进 restartRequired):开关改完立刻起停。
97
125
  this.mirror = mountMirror(ctx, { memoryDir: MEMORY_DIR, stateRoot: STATE_ROOT, readExternal: readExternalSettings })
@@ -578,7 +606,16 @@ markRemote(StarmapGateway, 'readFile', 'readFile')
578
606
  * `fs.writeText`:版本守卫 + 逐次沙箱策略(收窄到记忆目录),与 autodream 同一口径。
579
607
  */
580
608
  export class ConflictGateway extends TypertRemoteService {
581
- constructor(ctx) { super(ctx, 'conflict') }
609
+ /**
610
+ * @param {object} ctx
611
+ * @param {(name: string, content: string, opts?: object) => Promise<object>} [writeMemory]
612
+ * 记忆正文的写通道(本类 `MemoryGateway.writeFile`,三条闸门 + 版本守卫都在那边)。
613
+ * 只在 `applyResolution` 的「留远端」分支用到;缺了就回 `unsupported`,绝不自己另写一份。
614
+ */
615
+ constructor(ctx, writeMemory) {
616
+ super(ctx, 'conflict')
617
+ this.writeMemory = typeof writeMemory === 'function' ? writeMemory : null
618
+ }
582
619
 
583
620
  /** 解析「这次要标的是哪一方」:只能是记录里的 file 或 otherFile,否则 null。 */
584
621
  targetOf(record, requested) {
@@ -742,6 +779,66 @@ export class ConflictGateway extends TypertRemoteService {
742
779
  if (!removed.ok) return { ok: false, code: removed.code, error: removed.error }
743
780
  return { ok: true }
744
781
  }
782
+
783
+ /**
784
+ * 3.0.0:裁决一条**跨设备**冲突(`docs/3.0.0-arbitration-ui.md` §3.4)。
785
+ *
786
+ * 三条出路,判据是「保留哪一份」(不是「操作谁」):
787
+ * - `local` —— 保本地那份,把本地正文推到远端(远端在这期间又变过就 STALE,一个字不写)
788
+ * - `remote` —— 保远端那份,把远端正文写回本地(带 `expectedRevision`,本地被改过就拒)
789
+ * - `manual` —— 人自己改,插件一个字节都不写
790
+ *
791
+ * 这一层只做三件事:把 id / choice 收成字符串、把**写盘通道**注进去、把回来的收据补齐成
792
+ * 结果 schema 的形状。判断全在 `lib/sync/resolve.js`(状态机、基线、上行协议都在那里,
793
+ * 单测 `test/sync-arbitration-test.mjs` 逐条守着)—— 这里再判一遍就是第二个真相源。
794
+ *
795
+ * 失败**不抛**:`{ ok:false, code, error }` 与其余六条同一种回执风格。同时六个「回声」字段
796
+ * (choice / wrote / baseUpdated / status / recordId)一个都不省 —— 结果 schema 里它们必填,
797
+ * 而界面要靠 `wrote` 说清「已经写到远端了,只是记录没改成」这种半态,不能在传输层被 strip。
798
+ */
799
+ async applyResolution(opts) {
800
+ const id = typeof opts?.id === 'string' ? opts.id : ''
801
+ const choice = String(opts?.choice ?? '')
802
+ let res
803
+ try {
804
+ res = await resolveSyncConflict({
805
+ id,
806
+ choice,
807
+ memoryDir: MEMORY_DIR,
808
+ stateRoot: STATE_ROOT,
809
+ // 拿不到写通道时**照样调**:resolve 会把 `remote` 这一支判成 `unsupported`,
810
+ // 而 `local` / `manual` 不需要它(少一条通道不该让另外两条路也走不通)。
811
+ deps: { writeMemory: this.writeMemory ?? undefined },
812
+ })
813
+ } catch (err) {
814
+ return {
815
+ ok: false,
816
+ code: 'sync_failed',
817
+ error: `错误:sync_failed — ${err?.message ?? err}`,
818
+ choice,
819
+ wrote: 'none',
820
+ baseUpdated: false,
821
+ status: '',
822
+ recordId: id,
823
+ }
824
+ }
825
+ const receipt = {
826
+ ok: res?.ok === true,
827
+ choice: String(res?.choice ?? choice),
828
+ // 只有 resolve 明确说过的那两个值才算「写成了」;其余一律 `none`(不猜)。
829
+ wrote: res?.wrote === 'remote' || res?.wrote === 'local' ? res.wrote : 'none',
830
+ baseUpdated: res?.baseUpdated === true,
831
+ status: String(res?.status ?? ''),
832
+ recordId: String(res?.recordId ?? id),
833
+ }
834
+ // 基线写不进去是**部分成功**:文件已经写成,所以 baseError 与 code / error 分开报。
835
+ if (res?.baseError) receipt.baseError = String(res.baseError)
836
+ if (!receipt.ok) {
837
+ receipt.code = String(res?.code ?? 'sync_failed')
838
+ receipt.error = String(res?.error ?? `错误:${receipt.code} — 裁决没有完成`)
839
+ }
840
+ return receipt
841
+ }
745
842
  }
746
843
 
747
844
  markRemote(ConflictGateway, 'list', 'list')
@@ -750,9 +847,92 @@ markRemote(ConflictGateway, 'invalidate', 'invalidate')
750
847
  markRemote(ConflictGateway, 'dismiss', 'dismiss')
751
848
  markRemote(ConflictGateway, 'undo', 'undo')
752
849
  markRemote(ConflictGateway, 'removeRecord', 'removeRecord')
850
+ markRemote(ConflictGateway, 'applyResolution', 'applyResolution')
753
851
 
754
852
  // 2.1.8(N02):裁决入口整段按冲突 id 串行(第二方进队后重新读状态;理由见 util.js 的 serializeByKey)。
755
- serializeByKey(ConflictGateway, ['invalidate', 'dismiss', 'undo', 'removeRecord'])
853
+ // 3.0.0 的 `applyResolution` 一并纳入:它同样「先读记录、再写文件、再改记录」,
854
+ // 两次并发点击若各自读到 open,就会各写一次正文(远端那一条甚至会被推两次)。
855
+ serializeByKey(ConflictGateway, ['invalidate', 'dismiss', 'undo', 'removeRecord', 'applyResolution'])
856
+
857
+ /**
858
+ * 3.1.0:跨设备同步的面板面(`sync.*`)。业务全在 `lib/sync/`,这一层只做三件事:
859
+ * 把参数收成字符串、把**设置的兜底**接上、把回来的收据补齐成结果 schema 的形状
860
+ * (`runSyncAction` 的 `invalid` 分支不带 action/applied/report,`gateVerdict` 的
861
+ * deviceId 可能是 null —— schema 不该替下游造值,归一化就落在这里)。
862
+ */
863
+ export class SyncGateway extends TypertRemoteService {
864
+ constructor(ctx) {
865
+ super(ctx, 'sync')
866
+ }
867
+
868
+ /**
869
+ * 设备候选(`tailscale status --json`)。`listDevices` 自己**不抛** ——
870
+ * 没装 / 没登录 / JSON 坏都是值(`available:false` + 一句人话)。这里的 catch
871
+ * 兜的是它之外的意外:面板拿到 `ok:false` 就知道该看日志,而不是去手打 host。
872
+ */
873
+ async devices() {
874
+ try {
875
+ const { available, devices, reason } = await listDevices()
876
+ return { ok: true, available, devices, ...(typeof reason === 'string' && reason !== '' ? { reason } : {}) }
877
+ } catch (err) {
878
+ return { ok: false, available: false, devices: [], code: 'sync_failed', error: `错误:sync_failed — ${err?.message ?? err}` }
879
+ }
880
+ }
881
+
882
+ /**
883
+ * 一次同步动作。`host` / `remotePath` 的兜底顺序与工具面(`lib/tools/sync-tool.js`)一致:
884
+ * **传了就用传的**(去空白后非空),否则读设置里「外部访问 → 跨设备」那两项。
885
+ * 面板平时不传,只有用户临时改了没保存时才传 —— 所以这里不能反过来(设置优先)。
886
+ */
887
+ async run(opts) {
888
+ const action = String(opts?.action ?? '')
889
+ const configured = await readSyncSettings().catch(() => ({ sync: { host: '', remotePath: '' } }))
890
+ const host = String(opts?.host ?? '').trim() || configured.sync.host
891
+ const remotePath = String(opts?.remotePath ?? '').trim() || configured.sync.remotePath
892
+
893
+ let out
894
+ try {
895
+ out = await runSyncAction({
896
+ action,
897
+ host,
898
+ remotePath,
899
+ apply: opts?.apply === true,
900
+ confirm: opts?.confirm === true,
901
+ memoryDir: MEMORY_DIR,
902
+ stateRoot: STATE_ROOT,
903
+ })
904
+ } catch (err) {
905
+ out = { ok: false, code: 'sync_failed', error: `错误:sync_failed — ${err?.message ?? err}` }
906
+ }
907
+
908
+ const gate = out?.gate
909
+ return {
910
+ ok: out?.ok === true,
911
+ action: typeof out?.action === 'string' && out.action !== '' ? out.action : action,
912
+ applied: out?.applied === true,
913
+ report: typeof out?.report === 'string' ? out.report : '',
914
+ ...(gate !== null && typeof gate === 'object'
915
+ ? {
916
+ gate: {
917
+ allow: gate.allow === true,
918
+ reason: String(gate.reason ?? ''),
919
+ needConfirm: gate.needConfirm === true,
920
+ deviceId: String(gate.deviceId ?? ''),
921
+ deviceLabel: String(gate.deviceLabel ?? ''),
922
+ },
923
+ }
924
+ : {}),
925
+ // `code` / `error` 只在是字符串时才带上。**不用 `typeof x === 'string'` 的字面写法**:
926
+ // `test/code-registry-test.mjs` 的第二个模式会把 `.code === '<任意文本>'` 当成
927
+ // 「用了这个业务码」,于是 `'string'` 会被报成未登记的码(3.1.0 真踩过一次)。
928
+ ...(textOf(out?.code) ? { code: out.code } : {}),
929
+ ...(textOf(out?.error) ? { error: out.error } : {}),
930
+ }
931
+ }
932
+ }
933
+
934
+ markRemote(SyncGateway, 'devices', 'devices')
935
+ markRemote(SyncGateway, 'run', 'run')
756
936
 
757
937
  /**
758
938
  * autodream 的 remote 面:设置页「自动做梦」标签页唯一的数据通道。
@@ -81,6 +81,13 @@ export const CONFLICT_FIELD_LIMITS = Object.freeze({
81
81
  note: 4096,
82
82
  tool: 256,
83
83
  version: 256,
84
+ // 3.0.0 追加字段(同样是只增不改,`v` 仍是 1):`origin` 是「这条冲突是谁造的」,
85
+ // 它只可能是 `sync` / `autodream` / `manual` 之一(或不认识的同类短标识),16 字节够装;
86
+ // `host` / `remotePath` 只在 `origin === 'sync'` 时有值,照 `file` 那一档给 512 ——
87
+ // 远端记忆目录是真的会长,而这两个字段短到 48 字节就会把「哪台机器、哪个目录」切没。
88
+ origin: 16,
89
+ host: 512,
90
+ remotePath: 512,
84
91
  })
85
92
 
86
93
  /**
@@ -222,7 +229,8 @@ function shortDigest(parts) {
222
229
  *
223
230
  * 截断:各字段按 `CONFLICT_FIELD_LIMITS` 卡字节,截过就置 `truncated: true`。
224
231
  *
225
- * @param {{kind?, file?, expectedVersion?, actualVersion?, incoming?, onDisk?, note?, tool?, at?, id?}} input
232
+ * @param {{kind?, file?, expectedVersion?, actualVersion?, incoming?, onDisk?, note?, tool?,
233
+ * origin?, host?, remotePath?, at?, id?}} input
226
234
  */
227
235
  export function buildConflict(input) {
228
236
  const src = input && typeof input === 'object' ? input : {}
@@ -245,14 +253,24 @@ export function buildConflict(input) {
245
253
  const tool = clampText(src.tool, CONFLICT_FIELD_LIMITS.tool)
246
254
  const expectedVersion = clampText(versionText(src.expectedVersion), CONFLICT_FIELD_LIMITS.version)
247
255
  const actualVersion = clampText(versionText(src.actualVersion), CONFLICT_FIELD_LIMITS.version)
256
+ // 3.0.0 追加的来源三分。`origin` 不认识的字符串**原样保留**(与 `kind` 同一套哲学:
257
+ // 静默归一成某个已知值等于把「未知」伪装成「已知」);`host` / `remotePath` 只在
258
+ // `origin === 'sync'` 时有意义,别的来源传进来也照存(不替调用方做语义裁剪)。
259
+ const origin = clampText(src.origin, CONFLICT_FIELD_LIMITS.origin)
260
+ const host = clampText(src.host, CONFLICT_FIELD_LIMITS.host)
261
+ const remotePath = clampText(src.remotePath, CONFLICT_FIELD_LIMITS.remotePath)
248
262
 
249
263
  const truncated =
250
264
  file.cut || otherFile.cut || invalidatedFile.cut || decision.cut || appliedVersion.cut ||
251
- incoming.cut || onDisk.cut || note.cut || tool.cut || expectedVersion.cut || actualVersion.cut
265
+ incoming.cut || onDisk.cut || note.cut || tool.cut || expectedVersion.cut || actualVersion.cut ||
266
+ origin.cut || host.cut || remotePath.cut
252
267
 
253
268
  const stamp = compactStamp(at)
254
269
  // ⚠️ `otherFile` **只在非空时**进指纹:空串也拼进去的话,所有 1.x 老种类的 id 都会变 ——
255
270
  // 老记录还在盘上、新记录的 id 换了,就成了「同一件事两个身份」。
271
+ // ⚠️ 3.0.0 的 `origin` / `host` / `remotePath` **不进指纹**:它们描述的是「谁先撞上这件事」,
272
+ // 不是「冲突本身」。同一起冲突先被同步发现、再被 autodream 撞见,仍然是**一条**记录
273
+ // (`sameConflict` 是去重判据 —— 让它因为来源不同就判成两件事,跟这条指纹同一个病)。
256
274
  const digestParts = [kind, file.text, expectedVersion.text, actualVersion.text, incoming.text, onDisk.text]
257
275
  if (otherFile.text) digestParts.push(otherFile.text)
258
276
  const digest = shortDigest(digestParts)
@@ -277,6 +295,10 @@ export function buildConflict(input) {
277
295
  decidedAt,
278
296
  appliedVersion: appliedVersion.text,
279
297
  invalidatedFile: invalidatedFile.text,
298
+ // 3.0.0:来源(尾部追加,与 2.0.0 追加 `otherFile` / `decision` 同一个姿势)。
299
+ origin: origin.text,
300
+ host: host.text,
301
+ remotePath: remotePath.text,
280
302
  }
281
303
  }
282
304
 
@@ -381,6 +403,25 @@ export async function writeConflict(record, opts) {
381
403
  return { ok: true, bytes: Buffer.byteLength(text, 'utf8'), path, truncated }
382
404
  }
383
405
 
406
+ /**
407
+ * 老记录(≤ 2.x)**没有** 3.0.0 追加的三个来源键:读出来一律补成空串。
408
+ *
409
+ * 为什么不留给调用方各自兜底:`readConflict` 的 `record` 与 `listConflicts` 的 `items`
410
+ * 会被面板、注入侧、测试一起消费,每个消费点写一遍 `?? ''` 早晚漏一处 —— 而漏掉的那处
411
+ * 表现成「有 origin 的是 string、没有的是 undefined」:`=== 'sync'` 这类比较看不出问题,
412
+ * 走 `typeof` / `startsWith` 的分支却会崩。
413
+ *
414
+ * 三个键都**只补不覆盖**:有值就逐字保留(包括不认识的 origin,见 `buildConflict`)。
415
+ */
416
+ function withOriginFields(record) {
417
+ return {
418
+ ...record,
419
+ origin: typeof record.origin === 'string' ? record.origin : '',
420
+ host: typeof record.host === 'string' ? record.host : '',
421
+ remotePath: typeof record.remotePath === 'string' ? record.remotePath : '',
422
+ }
423
+ }
424
+
384
425
  /**
385
426
  * 解析一条记录的正文。形状不对就报原因 —— 判据是「读不读得出这是哪条冲突」:
386
427
  * 必须有非空 `id`,`status` 必须是已知状态。`kind` 允许未知(老记录 / 别处写的记录照读)。
@@ -425,7 +466,9 @@ export async function readConflict(id, opts) {
425
466
  const parsed = parseConflictText(text)
426
467
  if (!parsed.ok) return { ok: false, code: 'malformed', path, error: parsed.reason }
427
468
 
428
- const record = { ...parsed.record, id: cid }
469
+ // 整份 JSON 反序列化 → 不认识的键**原样保留**(新字段天然读得出来);
470
+ // 只是老记录缺的那三个来源键在这里补成空串(`withOriginFields`)。
471
+ const record = withOriginFields({ ...parsed.record, id: cid })
429
472
  const warnings = []
430
473
  if (parsed.record.id !== cid) {
431
474
  warnings.push(`文件内声明的冲突 id(${parsed.record.id})与文件名(${cid})不一致,已按文件名归一`)
@@ -586,7 +629,7 @@ export async function listConflicts(opts) {
586
629
  broken.push(name)
587
630
  continue
588
631
  }
589
- items.push({ ...parsed.record, id })
632
+ items.push(withOriginFields({ ...parsed.record, id }))
590
633
  }
591
634
 
592
635
  // 新的在前(队列的第一眼应该是最新那条);没有 at 的排在后面,同档按 id 排,保证顺序确定。
@@ -614,6 +657,12 @@ export function summarizeConflict(record) {
614
657
  decidedAt: typeof r.decidedAt === 'string' ? r.decidedAt : '',
615
658
  appliedVersion: typeof r.appliedVersion === 'string' ? r.appliedVersion : '',
616
659
  invalidatedFile: typeof r.invalidatedFile === 'string' ? r.invalidatedFile : '',
660
+ // 3.0.0:来源三字段。缺省空串 = 老记录 = 面板按 `'manual'` 处理(additive 契约)。
661
+ // 面板靠它把「跨设备差异」与本地冲突分开渲染 —— 靠 `kind` 猜不可靠:
662
+ // `both-changed`(同步)与 autodream 的 `external_change` 语义上都是「两边都动过」。
663
+ origin: typeof r.origin === 'string' ? r.origin : '',
664
+ host: typeof r.host === 'string' ? r.host : '',
665
+ remotePath: typeof r.remotePath === 'string' ? r.remotePath : '',
617
666
  truncated: r.truncated === true,
618
667
  }
619
668
  }
@@ -88,6 +88,34 @@ export const CODES = Object.freeze({
88
88
  // 写协议已有的码(`write-protocol.js` 的 `ERR_ALREADY_EXISTS`);拉取把它当「降级成冲突」的信号,
89
89
  // 所以这里必须能按值匹配。
90
90
  already_exists: 'already_exists',
91
+ // ── 跨设备推送(3.0.0)──
92
+ // 写入门:远端不是 sage-mem 库 / 身份文件读不出。与「连不上」分开 ——
93
+ // 连不上是抛错(异常),门不过是一个明确的结论(返回值)。
94
+ gate: 'gate',
95
+ // 写入门要求人点头(首次向这台设备推送,或远端换了库)。
96
+ need_confirm: 'need_confirm',
97
+ // 上行没走完:传输断了、超时、或远端脚本在提交之前停下。三条的后果相同 ——
98
+ // 「不知道进去了几个」,所以同一个码,靠 error 文案区分。
99
+ upload_failed: 'upload_failed',
100
+ // 本地文件在报告之后被改过:预演里没有它,就不推它。与 `stale_remote` 正好对称
101
+ // (一个错在本地并发,一个错在远端并发)。
102
+ stale_local: 'stale_local',
103
+ // 远端没有回报某一条(脚本中途退出):按未完成处理,绝不默认成功。
104
+ no_report: 'no_report',
105
+ // ── 跨设备裁决(3.0.0 第 4 步)──
106
+ // 这六个码由 `sync/resolve.js` 返回。它们**不经过 `code: 'x'` 字面量**(走的是
107
+ // `bad(code, …)` 的变量),所以 `code-registry-test` 的扫描抓不到 —— 正因为抓不到,
108
+ // 更要按契约登记在这里:清单是给人和下一个维护者看的,不是只给测试看的。
109
+ not_open: 'not_open',
110
+ not_sync: 'not_sync',
111
+ no_remote: 'no_remote',
112
+ local_missing: 'local_missing',
113
+ conflict: 'conflict',
114
+ fatal: 'fatal',
115
+ // 远端脚本对某一条回了 `FAIL <原因>`(`mv` 失败、备份失败…)。
116
+ // 与 `upload_failed` 分开:那个是**整批传输层面**没走完(ssh 断了 / 超时),
117
+ // 这个是「传到了,但远端那一条没落地」—— 前者不知道进去了几个,后者知道。
118
+ failed: 'failed',
91
119
  // ── 其它 ──
92
120
  memory_unavailable: 'memory_unavailable',
93
121
  flood: 'flood',
package/lib/sync/base.js CHANGED
@@ -87,3 +87,127 @@ export async function writeBase(stateRoot, { files, host, remotePath, at }) {
87
87
  await writeFileAtomic(basePathOf(stateRoot), `${JSON.stringify(payload, null, 2)}\n`)
88
88
  return payload
89
89
  }
90
+
91
+ // ── 推送侧的基线(3.0.0)────────────────────────────────────────────
92
+ //
93
+ // 与上面的 `base.json` **不是一件事**,别合并:
94
+ // - `base.json` 记的是「上次同步时远端长什么样」(内容侧,用来分类);
95
+ // - `push-baseline.json` 记的是「我确认过这台远端是我的库」(信任侧,用来决定要不要问人)。
96
+ //
97
+ // 为什么信任侧不写到远端去:写远端正是这道门要拦的事。确认是**本机**的决定,
98
+ // 痕迹也只该留在本机 —— 换句话说,B 机相不相信 A 机,是 B 机自己的事。
99
+ //
100
+ // 为什么按 (host, remotePath) 记而不是只按 host:同一台机器上可以有两个记忆库
101
+ // (比如一份工作用、一份私人),确认过其中一个不等于确认过另一个。
102
+
103
+ /** 推送基线格式版本。改了结构要 +1,旧版会被当成「没确认过」(最多多问一次,不会误放行)。 */
104
+ export const PUSH_BASE_VERSION = 1
105
+
106
+ /**
107
+ * @param {string} stateRoot
108
+ * @returns {string} `push-baseline.json` 的绝对路径
109
+ */
110
+ export function pushBasePathOf(stateRoot) {
111
+ return join(stateRoot, 'sync', 'push-baseline.json')
112
+ }
113
+
114
+ /**
115
+ * 归一一个远程标识。**比较与存储都走它**,否则 `~/mem` 与 `~/mem/` 会变成两个远端。
116
+ *
117
+ * @param {string} host
118
+ * @param {string} remotePath
119
+ * @returns {{host: string, remotePath: string}}
120
+ */
121
+ export function remoteKeyOf(host, remotePath) {
122
+ return {
123
+ host: String(host ?? '').trim(),
124
+ remotePath: String(remotePath ?? '').trim().replace(/\/+$/, ''),
125
+ }
126
+ }
127
+
128
+ /**
129
+ * 读推送基线。没有 / 坏了 / 版本不对 → 空表(**宁可多问一次确认,也不要误放行**)。
130
+ *
131
+ * @param {string} stateRoot
132
+ * @returns {Promise<{version:number, remotes: Array<{host:string, remotePath:string, deviceId:string, confirmedAt:string|null}>}>}
133
+ */
134
+ export async function readPushBaseline(stateRoot) {
135
+ const empty = { version: PUSH_BASE_VERSION, remotes: [] }
136
+ let raw
137
+ try {
138
+ raw = await readFile(pushBasePathOf(stateRoot), 'utf8')
139
+ } catch {
140
+ return empty
141
+ }
142
+ let parsed
143
+ try {
144
+ parsed = JSON.parse(raw)
145
+ } catch {
146
+ return empty
147
+ }
148
+ if (!parsed || typeof parsed !== 'object' || parsed.version !== PUSH_BASE_VERSION) return empty
149
+
150
+ const remotes = []
151
+ for (const item of Array.isArray(parsed.remotes) ? parsed.remotes : []) {
152
+ if (!item || typeof item !== 'object') continue
153
+ const key = remoteKeyOf(item.host, item.remotePath)
154
+ if (key.host === '' || key.remotePath === '') continue
155
+ remotes.push({
156
+ ...key,
157
+ deviceId: typeof item.deviceId === 'string' ? item.deviceId.trim().toLowerCase() : '',
158
+ confirmedAt: typeof item.confirmedAt === 'string' ? item.confirmedAt : null,
159
+ })
160
+ }
161
+ return { version: PUSH_BASE_VERSION, remotes }
162
+ }
163
+
164
+ /**
165
+ * 查「这条远程确认过没有」。
166
+ *
167
+ * @param {string} stateRoot
168
+ * @param {{host: string, remotePath: string}} where
169
+ * @returns {Promise<{deviceId: string, confirmedAt: string|null} | null>}
170
+ */
171
+ export async function readConfirmedRemote(stateRoot, { host, remotePath } = {}) {
172
+ const key = remoteKeyOf(host, remotePath)
173
+ if (key.host === '' || key.remotePath === '') return null
174
+ const base = await readPushBaseline(stateRoot)
175
+ const hit = base.remotes.find((r) => r.host === key.host && r.remotePath === key.remotePath)
176
+ if (!hit) return null
177
+ return { deviceId: hit.deviceId, confirmedAt: hit.confirmedAt }
178
+ }
179
+
180
+ /**
181
+ * 记下「人已经确认过这条远程」。**只在 `apply` 且带了 `confirm` 时调**——
182
+ * 一次预演不该产生信任。
183
+ *
184
+ * 幂等:同一条远程重复确认只保留一条,`confirmedAt` 取最后一次。
185
+ * 换了 `deviceId` 也照写(人刚刚重新点头的就是新身份)。
186
+ *
187
+ * @param {string} stateRoot
188
+ * @param {object} input
189
+ * @param {string} input.host
190
+ * @param {string} input.remotePath
191
+ * @param {string} input.deviceId
192
+ * @param {string} [input.at]
193
+ * @returns {Promise<object>} 落盘的那份 payload
194
+ */
195
+ export async function rememberConfirmedRemote(stateRoot, { host, remotePath, deviceId, at }) {
196
+ const key = remoteKeyOf(host, remotePath)
197
+ if (key.host === '' || key.remotePath === '') throw new Error('记确认需要一个 host 与 remotePath')
198
+ const base = await readPushBaseline(stateRoot)
199
+ const rest = base.remotes.filter((r) => !(r.host === key.host && r.remotePath === key.remotePath))
200
+ const remotes = [...rest, {
201
+ ...key,
202
+ deviceId: String(deviceId ?? '').trim().toLowerCase(),
203
+ confirmedAt: at ?? new Date().toISOString(),
204
+ }].sort((a, b) => {
205
+ if (a.host !== b.host) return a.host < b.host ? -1 : 1
206
+ return a.remotePath < b.remotePath ? -1 : a.remotePath > b.remotePath ? 1 : 0
207
+ })
208
+
209
+ const payload = { version: PUSH_BASE_VERSION, remotes }
210
+ await mkdir(join(stateRoot, 'sync'), { recursive: true })
211
+ await writeFileAtomic(pushBasePathOf(stateRoot), `${JSON.stringify(payload, null, 2)}\n`)
212
+ return payload
213
+ }