sage-mem 2.33.4 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +38 -1
- package/README.md +38 -1
- package/lib/assembly/tools-mount.js +4 -1
- package/lib/autodream/tools.js +5 -0
- package/lib/client.js +674 -0
- package/lib/index.js +89 -3
- package/lib/memory/conflicts.js +53 -4
- package/lib/shared/codes.js +28 -0
- package/lib/sync/base.js +124 -0
- package/lib/sync/gate.js +303 -0
- package/lib/sync/instance.js +138 -0
- package/lib/sync/policy.js +212 -0
- package/lib/sync/pull.js +6 -0
- package/lib/sync/push.js +522 -0
- package/lib/sync/remote.js +139 -10
- package/lib/sync/resolve.js +358 -0
- package/lib/sync/upload.js +372 -0
- package/lib/tools/sync-tool.js +127 -1
- package/lib/typert/schemas.js +38 -0
- package/lib/typert.host.js +16 -0
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -38,6 +38,9 @@ import { checkUpdate as checkUpdateImpl } from './update.js'
|
|
|
38
38
|
import { applySettingsPatch, MAX_RAW_BYTES, parseExperimentalPatch, parseUiPatch, pendingExperimental, pendingUi, rawName, readExternalSettings, readReservedFile, readSettingsFileDetailed, readSettingsSnapshot, 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
|
+
// 3.0.0:跨设备冲突的裁决实现(`conflict/applyResolution` 背后的那一步)。
|
|
43
|
+
import { resolveSyncConflict } from './sync/resolve.js'
|
|
41
44
|
|
|
42
45
|
/**
|
|
43
46
|
* 读方法的拒绝:**抛**一个带 `.code` 的 Error(写方法返回 `{ok:false, code}` 回执,见 prepareWrite)。
|
|
@@ -73,7 +76,12 @@ export class MemoryGateway extends TypertRemoteService {
|
|
|
73
76
|
// 2.0.0:冲突裁决入口(列表 / 读 / 标失效 / 驳回 / 撤销 / 删除记录)—— conflict.* 服务。
|
|
74
77
|
// 与 memory / starmap 分开成独立 namespace:混成一个面会让「读记忆」与「改记忆的有效性」
|
|
75
78
|
// 共用一张契约表,而后者是**写用户文件**的动作。
|
|
76
|
-
|
|
79
|
+
//
|
|
80
|
+
// 3.0.0:把**本类的写盘能力**以函数形式交给它(`applyResolution` 的「留远端」要把正文写回本地)。
|
|
81
|
+
// 为什么走参数而不是在 ConflictGateway 里 `ctx.get('memory')`:此刻正在注册这个服务本身
|
|
82
|
+
// (与 tools-mount.js 头注同一条时序事实 —— 构造期读自己会拿到 undefined 或半成品)。
|
|
83
|
+
// 也不许在 lib/sync/ 里另写一份带 `expectedRevision` 的写盘:一条记忆的落盘口径只该有一处。
|
|
84
|
+
new ConflictGateway(ctx, (name, content, opts) => this.writeFile(name, content, opts))
|
|
77
85
|
|
|
78
86
|
// 四块挂载(1.2.0 从构造函数里搬出的四段)。顺序保持原样:
|
|
79
87
|
// autodream → 检索工具 → 观测 → 写入门。
|
|
@@ -92,6 +100,12 @@ export class MemoryGateway extends TypertRemoteService {
|
|
|
92
100
|
// 2.17.0:压缩前提醒(实验性,默认关;关着时每步只是一次开关读取)。
|
|
93
101
|
mountPreCompact(ctx, { memoryDir: MEMORY_DIR })
|
|
94
102
|
|
|
103
|
+
// 3.0.0:本机设备身份(`<状态根>/instance.json`,只记 id / 机器名 / 创建时间)。
|
|
104
|
+
// **必须在装配期建好**:别的机器要推给我时,写入门第二道要能在我的状态根里读到它;
|
|
105
|
+
// 只在「我自己推送」时才创建,会让一台只收不推的机器永远收不到东西。
|
|
106
|
+
// 失败不阻断(只读盘 / 权限):后果只是别人推给我时要多确认一次,那是可接受的降级。
|
|
107
|
+
ensureLocalInstance(STATE_ROOT).catch(() => {})
|
|
108
|
+
|
|
95
109
|
// 2.25.0:外部访问读侧(白名单导出 + 只读 MCP)。默认关,关着时一行都不跑。
|
|
96
110
|
// `readExternal` 给的是**现读**设置(不进 restartRequired):开关改完立刻起停。
|
|
97
111
|
this.mirror = mountMirror(ctx, { memoryDir: MEMORY_DIR, stateRoot: STATE_ROOT, readExternal: readExternalSettings })
|
|
@@ -578,7 +592,16 @@ markRemote(StarmapGateway, 'readFile', 'readFile')
|
|
|
578
592
|
* `fs.writeText`:版本守卫 + 逐次沙箱策略(收窄到记忆目录),与 autodream 同一口径。
|
|
579
593
|
*/
|
|
580
594
|
export class ConflictGateway extends TypertRemoteService {
|
|
581
|
-
|
|
595
|
+
/**
|
|
596
|
+
* @param {object} ctx
|
|
597
|
+
* @param {(name: string, content: string, opts?: object) => Promise<object>} [writeMemory]
|
|
598
|
+
* 记忆正文的写通道(本类 `MemoryGateway.writeFile`,三条闸门 + 版本守卫都在那边)。
|
|
599
|
+
* 只在 `applyResolution` 的「留远端」分支用到;缺了就回 `unsupported`,绝不自己另写一份。
|
|
600
|
+
*/
|
|
601
|
+
constructor(ctx, writeMemory) {
|
|
602
|
+
super(ctx, 'conflict')
|
|
603
|
+
this.writeMemory = typeof writeMemory === 'function' ? writeMemory : null
|
|
604
|
+
}
|
|
582
605
|
|
|
583
606
|
/** 解析「这次要标的是哪一方」:只能是记录里的 file 或 otherFile,否则 null。 */
|
|
584
607
|
targetOf(record, requested) {
|
|
@@ -742,6 +765,66 @@ export class ConflictGateway extends TypertRemoteService {
|
|
|
742
765
|
if (!removed.ok) return { ok: false, code: removed.code, error: removed.error }
|
|
743
766
|
return { ok: true }
|
|
744
767
|
}
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* 3.0.0:裁决一条**跨设备**冲突(`docs/3.0.0-arbitration-ui.md` §3.4)。
|
|
771
|
+
*
|
|
772
|
+
* 三条出路,判据是「保留哪一份」(不是「操作谁」):
|
|
773
|
+
* - `local` —— 保本地那份,把本地正文推到远端(远端在这期间又变过就 STALE,一个字不写)
|
|
774
|
+
* - `remote` —— 保远端那份,把远端正文写回本地(带 `expectedRevision`,本地被改过就拒)
|
|
775
|
+
* - `manual` —— 人自己改,插件一个字节都不写
|
|
776
|
+
*
|
|
777
|
+
* 这一层只做三件事:把 id / choice 收成字符串、把**写盘通道**注进去、把回来的收据补齐成
|
|
778
|
+
* 结果 schema 的形状。判断全在 `lib/sync/resolve.js`(状态机、基线、上行协议都在那里,
|
|
779
|
+
* 单测 `test/sync-arbitration-test.mjs` 逐条守着)—— 这里再判一遍就是第二个真相源。
|
|
780
|
+
*
|
|
781
|
+
* 失败**不抛**:`{ ok:false, code, error }` 与其余六条同一种回执风格。同时六个「回声」字段
|
|
782
|
+
* (choice / wrote / baseUpdated / status / recordId)一个都不省 —— 结果 schema 里它们必填,
|
|
783
|
+
* 而界面要靠 `wrote` 说清「已经写到远端了,只是记录没改成」这种半态,不能在传输层被 strip。
|
|
784
|
+
*/
|
|
785
|
+
async applyResolution(opts) {
|
|
786
|
+
const id = typeof opts?.id === 'string' ? opts.id : ''
|
|
787
|
+
const choice = String(opts?.choice ?? '')
|
|
788
|
+
let res
|
|
789
|
+
try {
|
|
790
|
+
res = await resolveSyncConflict({
|
|
791
|
+
id,
|
|
792
|
+
choice,
|
|
793
|
+
memoryDir: MEMORY_DIR,
|
|
794
|
+
stateRoot: STATE_ROOT,
|
|
795
|
+
// 拿不到写通道时**照样调**:resolve 会把 `remote` 这一支判成 `unsupported`,
|
|
796
|
+
// 而 `local` / `manual` 不需要它(少一条通道不该让另外两条路也走不通)。
|
|
797
|
+
deps: { writeMemory: this.writeMemory ?? undefined },
|
|
798
|
+
})
|
|
799
|
+
} catch (err) {
|
|
800
|
+
return {
|
|
801
|
+
ok: false,
|
|
802
|
+
code: 'sync_failed',
|
|
803
|
+
error: `错误:sync_failed — ${err?.message ?? err}`,
|
|
804
|
+
choice,
|
|
805
|
+
wrote: 'none',
|
|
806
|
+
baseUpdated: false,
|
|
807
|
+
status: '',
|
|
808
|
+
recordId: id,
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
const receipt = {
|
|
812
|
+
ok: res?.ok === true,
|
|
813
|
+
choice: String(res?.choice ?? choice),
|
|
814
|
+
// 只有 resolve 明确说过的那两个值才算「写成了」;其余一律 `none`(不猜)。
|
|
815
|
+
wrote: res?.wrote === 'remote' || res?.wrote === 'local' ? res.wrote : 'none',
|
|
816
|
+
baseUpdated: res?.baseUpdated === true,
|
|
817
|
+
status: String(res?.status ?? ''),
|
|
818
|
+
recordId: String(res?.recordId ?? id),
|
|
819
|
+
}
|
|
820
|
+
// 基线写不进去是**部分成功**:文件已经写成,所以 baseError 与 code / error 分开报。
|
|
821
|
+
if (res?.baseError) receipt.baseError = String(res.baseError)
|
|
822
|
+
if (!receipt.ok) {
|
|
823
|
+
receipt.code = String(res?.code ?? 'sync_failed')
|
|
824
|
+
receipt.error = String(res?.error ?? `错误:${receipt.code} — 裁决没有完成`)
|
|
825
|
+
}
|
|
826
|
+
return receipt
|
|
827
|
+
}
|
|
745
828
|
}
|
|
746
829
|
|
|
747
830
|
markRemote(ConflictGateway, 'list', 'list')
|
|
@@ -750,9 +833,12 @@ markRemote(ConflictGateway, 'invalidate', 'invalidate')
|
|
|
750
833
|
markRemote(ConflictGateway, 'dismiss', 'dismiss')
|
|
751
834
|
markRemote(ConflictGateway, 'undo', 'undo')
|
|
752
835
|
markRemote(ConflictGateway, 'removeRecord', 'removeRecord')
|
|
836
|
+
markRemote(ConflictGateway, 'applyResolution', 'applyResolution')
|
|
753
837
|
|
|
754
838
|
// 2.1.8(N02):裁决入口整段按冲突 id 串行(第二方进队后重新读状态;理由见 util.js 的 serializeByKey)。
|
|
755
|
-
|
|
839
|
+
// 3.0.0 的 `applyResolution` 一并纳入:它同样「先读记录、再写文件、再改记录」,
|
|
840
|
+
// 两次并发点击若各自读到 open,就会各写一次正文(远端那一条甚至会被推两次)。
|
|
841
|
+
serializeByKey(ConflictGateway, ['invalidate', 'dismiss', 'undo', 'removeRecord', 'applyResolution'])
|
|
756
842
|
|
|
757
843
|
/**
|
|
758
844
|
* autodream 的 remote 面:设置页「自动做梦」标签页唯一的数据通道。
|
package/lib/memory/conflicts.js
CHANGED
|
@@ -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?,
|
|
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
|
-
|
|
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
|
}
|
package/lib/shared/codes.js
CHANGED
|
@@ -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
|
+
}
|