dsh-config-manager 0.4.0 → 0.4.1

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.
Files changed (38) hide show
  1. package/lib/client.d.ts +21 -2
  2. package/lib/client.js +558 -550
  3. package/lib/core/messages-core.d.ts +1 -0
  4. package/lib/core/messages-core.js +2 -0
  5. package/lib/core/migration-history.d.ts +18 -2
  6. package/lib/core/migration-history.js +19 -3
  7. package/lib/index.d.ts +1 -1
  8. package/lib/index.js +3 -3
  9. package/lib/sync/autosync-scheduler.js +6 -2
  10. package/lib/sync/baseline-heal.d.ts +35 -0
  11. package/lib/sync/baseline-heal.js +39 -0
  12. package/lib/sync/push-precheck.d.ts +35 -0
  13. package/lib/sync/push-precheck.js +58 -0
  14. package/lib/sync/sync-engine.d.ts +9 -12
  15. package/lib/sync/sync-engine.js +24 -43
  16. package/lib/ui/history-model.js +3 -2
  17. package/lib/ui/overview-view.d.ts +3 -3
  18. package/lib/ui/overview-view.js +9 -1
  19. package/package.json +1 -1
  20. package/src/client/history/history-locales.ts +2 -0
  21. package/src/client/home/HomePanel.tsx +9 -3
  22. package/src/client/locales.ts +2 -0
  23. package/src/client/sync/history-model.ts +3 -0
  24. package/src/client/sync/sync-locales.ts +2 -0
  25. package/src/core/messages-core.ts +2 -0
  26. package/src/core/migration-history.test.ts +19 -0
  27. package/src/core/migration-history.ts +28 -5
  28. package/src/index.ts +3 -3
  29. package/src/sync/autosync-scheduler.test.ts +23 -0
  30. package/src/sync/autosync-scheduler.ts +6 -2
  31. package/src/sync/baseline-heal.ts +74 -0
  32. package/src/sync/push-precheck.ts +75 -0
  33. package/src/sync/sync-engine.test.ts +88 -0
  34. package/src/sync/sync-engine.ts +33 -43
  35. package/src/ui/history-model.test.ts +2 -1
  36. package/src/ui/history-model.ts +3 -2
  37. package/src/ui/overview-view.test.ts +12 -0
  38. package/src/ui/overview-view.ts +12 -4
@@ -269,6 +269,7 @@ export const zh = {
269
269
  'history.autosyncPush': '上传',
270
270
  'history.autosyncBoth': '双向',
271
271
  'history.autosyncReasonConflict': '冲突',
272
+ 'history.autosyncReasonBaselineAdopted': '基线已自动收养(上次推送在记录基线前被打断)',
272
273
  'history.autosyncReasonNoRemote': '无远端快照',
273
274
  'history.autosyncReasonNotConfigured': '未配置仓库',
274
275
  'history.autosyncReasonNetwork': '网络问题',
@@ -713,6 +714,7 @@ export const en: Record<keyof typeof zh, string> = {
713
714
  'history.autosyncPush': 'Push',
714
715
  'history.autosyncBoth': 'Both',
715
716
  'history.autosyncReasonConflict': 'Conflict',
717
+ 'history.autosyncReasonBaselineAdopted': 'Baseline adopted automatically (the previous push was interrupted before recording it)',
716
718
  'history.autosyncReasonNoRemote': 'No remote snapshot',
717
719
  'history.autosyncReasonNotConfigured': 'No repository configured',
718
720
  'history.autosyncReasonNetwork': 'Network issue',
@@ -91,6 +91,7 @@ export const zh = {
91
91
  'core.migrationHistory.resultSuccess': '成功',
92
92
  'core.migrationHistory.resultFailed': '失败',
93
93
  'core.migrationHistory.resultSkipped': '跳过',
94
+ 'core.migrationHistory.resultPending': '待裁决',
94
95
 
95
96
  // ---------- local-plugin-pack ----------
96
97
  'core.localPluginPack.dirCreateFailed': '本地插件打包目录创建失败,已跳过全部本地插件: {reason}',
@@ -405,6 +406,7 @@ export const en: Record<keyof typeof zh, string> = {
405
406
  'core.migrationHistory.resultSuccess': 'success',
406
407
  'core.migrationHistory.resultFailed': 'failed',
407
408
  'core.migrationHistory.resultSkipped': 'skipped',
409
+ 'core.migrationHistory.resultPending': 'needs decision',
408
410
 
409
411
  // ---------- local-plugin-pack ----------
410
412
  'core.localPluginPack.dirCreateFailed': 'Failed to create the local plugin packing directory; skipped all local plugins: {reason}',
@@ -334,6 +334,25 @@ test('QUERYABLE:parseHistoryQuery 解析过滤参数并丢弃非法 kind', ()
334
334
  assert.deepEqual(q.sections, ['plugins']);
335
335
  });
336
336
 
337
+ test('0.4.1 待裁决:result=pending 可落盘读回、可被查询过滤、导出写人话而非裸枚举', async (t) => {
338
+ const dir = tmp(t);
339
+ const appended = await mkStore(dir).append(makeRaw({ kind: 'autosync', result: 'pending', summary: '自动同步有 1 个分区待裁决' }));
340
+ assert.equal(appended.ok, true);
341
+
342
+ const read = await mkStore(dir).read();
343
+ assert.deepEqual(read.corrupted, [], 'pending 是合法结果 —— 不得被当成篡改条目静默丢弃');
344
+ assert.equal(read.entries.length, 1);
345
+ assert.equal(read.entries[0]!.result, 'pending', '读回必须保留 pending(否则「待裁决」在刷新后消失)');
346
+
347
+ assert.deepEqual(parseHistoryQuery({ result: 'pending,failed' }).result, ['pending', 'failed'], '过滤白名单必须认 pending');
348
+ assert.equal(queryHistory(read.entries, { result: ['pending'] }).length, 1);
349
+ assert.equal(queryHistory(read.entries, { result: ['failed'] }).length, 0, 'pending 不得被当成 failed 命中');
350
+
351
+ const md = renderExport(read.entries, 'markdown', 'zh');
352
+ assert.match(md, /待裁决/, '导出要写人话');
353
+ assert.ok(!md.includes('| pending |'), '原文列绝不出现裸枚举值');
354
+ });
355
+
337
356
  test('EXPORTABLE:renderExport json 输出合法 JSON + 统计', () => {
338
357
  const entries = [sanitizeEntry(makeRaw()), sanitizeEntry(makeRaw({ kind: 'restore', result: 'failed' }))];
339
358
  const json = renderExport(entries, 'json');
@@ -79,8 +79,29 @@ const MIGRATION_KINDS = [
79
79
  /** §5 覆盖的操作 kind(COMPLETE 不变量;常量枚举,天然非敏感)。 */
80
80
  export type MigrationKind = (typeof MIGRATION_KINDS)[number];
81
81
 
82
- /** 操作结果。 */
83
- export type MigrationResult = 'success' | 'failed' | 'skipped';
82
+ /**
83
+ * 操作结果。
84
+ *
85
+ * 'pending'(0.4.1):操作**跑完了但仍有待裁决项**(自动同步上传成功、下行冲突未裁决;
86
+ * 合并已应用一部分)。它不是 failed —— 网络/凭据/repo 都是好的;也不是 skipped ——
87
+ * 那一轮确实做了事。旧实现把 partial 直接折成 'failed',用户看到「自动同步 失败」而
88
+ * 实际只需要在同步页确认一次冲突。读侧(parseEntry / query 解析)必须接受该值,
89
+ * 否则含 pending 的历史条目会被整条丢弃。
90
+ */
91
+ export type MigrationResult = 'success' | 'failed' | 'skipped' | 'pending';
92
+
93
+ /**
94
+ * 自动同步一轮的状态 → 历史 result(宿主 appendHistoryFn 的唯一映射,0.4.1)。
95
+ *
96
+ * 关键一条:`partial`(跑完了但仍有待裁决分区)**不是** failed —— 通道与凭据都正常,
97
+ * 只是需要用户在同步页确认一次冲突。落成 failed 会让首页红字报「同步失败」,
98
+ * 用户据此去查网络/凭据,方向完全错。
99
+ */
100
+ export function historyResultFromAutosyncStatus(status: 'success' | 'skipped' | 'partial' | 'failed'): MigrationResult {
101
+ if (status === 'success') return 'success';
102
+ if (status === 'skipped') return 'skipped';
103
+ return status === 'partial' ? 'pending' : 'failed';
104
+ }
84
105
 
85
106
  /** 触发来源(常量)。 */
86
107
  export type MigrationSource = 'api' | 'autosync' | 'backup-scheduler' | 'recovery' | 'cli' | 'internal';
@@ -308,7 +329,7 @@ function parseEntry(text: string): StoredMigrationHistoryEntry | null {
308
329
  if (p.schemaVersion !== MIGRATION_HISTORY_SCHEMA_VERSION) return null;
309
330
  if (!isValidMigrationKind(p.kind)) return null;
310
331
  if (typeof p.at !== 'string' || p.at === '') return null;
311
- if (!['success', 'failed', 'skipped'].includes(p.result)) return null;
332
+ if (!['success', 'failed', 'skipped', 'pending'].includes(p.result)) return null;
312
333
  if (typeof p.source !== 'string') return null;
313
334
  if (typeof p.summary !== 'string') return null;
314
335
  // 可选字段校验
@@ -479,7 +500,9 @@ export function renderExport(entries: StoredMigrationHistoryEntry[], format: Exp
479
500
  ? T('core.migrationHistory.resultSuccess')
480
501
  : r === 'failed'
481
502
  ? T('core.migrationHistory.resultFailed')
482
- : T('core.migrationHistory.resultSkipped');
503
+ : r === 'pending'
504
+ ? T('core.migrationHistory.resultPending')
505
+ : T('core.migrationHistory.resultSkipped');
483
506
 
484
507
  if (format === 'json') {
485
508
  const stats = summarizeHistory(entries);
@@ -506,7 +529,7 @@ export function parseHistoryQuery(raw: Record<string, unknown>): MigrationQuery
506
529
  const kinds = parseList(raw['kind']);
507
530
  if (kinds.length > 0) q.kinds = kinds.filter(isValidMigrationKind);
508
531
  const results = parseList(raw['result']);
509
- if (results.length > 0) q.result = results.filter((r): r is MigrationResult => r === 'success' || r === 'failed' || r === 'skipped');
532
+ if (results.length > 0) q.result = results.filter((r): r is MigrationResult => r === 'success' || r === 'failed' || r === 'skipped' || r === 'pending');
510
533
  const sections = parseList(raw['sections']);
511
534
  if (sections.length > 0) q.sections = sections;
512
535
  const from = parseNum(raw['from']);
package/src/index.ts CHANGED
@@ -132,7 +132,7 @@ import type { RetentionPolicy } from './sync/retention-policy.ts'
132
132
  import type { PruneSelector } from './core/backup.ts'
133
133
  import { selectPruneCandidates } from './core/backup.ts'
134
134
  import { appendAutosyncEntry } from './sync/sync-history.ts'
135
- import { MigrationStore, type MigrationKind, type MigrationResult, MIGRATION_HISTORY_DIR } from './core/migration-history.ts'
135
+ import { MigrationStore, type MigrationKind, type MigrationResult, historyResultFromAutosyncStatus, MIGRATION_HISTORY_DIR } from './core/migration-history.ts'
136
136
  import { createHistoryPruner } from './core/history-prune.ts'
137
137
  import { validateRepoUrl, validateWebDavUrl, isWebDavConfig, isS3Config, isGistConfig, channelOf, parseSyncChannel, SYNC_CHANNELS, GIST_PROVIDER, isS3CompatProvider, validateCloudChannelInput, cloudSecretRef } from './sync/sync-config.ts'
138
138
  import {
@@ -183,7 +183,7 @@ export const name = 'config-manager'
183
183
  export const inject = ['settings', 'credentials']
184
184
 
185
185
  /** Plugin version, kept in sync with package.json ("version"). */
186
- export const PLUGIN_VERSION = '0.4.0'
186
+ export const PLUGIN_VERSION = '0.4.1'
187
187
 
188
188
  /** Plugin own package name — excluded from its own exported plugins list. */
189
189
  const PLUGIN_NAME = 'dsh-config-manager'
@@ -3007,7 +3007,7 @@ function makeRoutes(deps: RoutesDeps): { routes: WebRoute[]; scheduler: AutoSync
3007
3007
  await appendAutosyncEntry(syncDir, entry).catch(() => undefined)
3008
3008
  await history.append({
3009
3009
  kind: 'autosync',
3010
- result: entry.status === 'success' ? 'success' : entry.status === 'skipped' ? 'skipped' : 'failed',
3010
+ result: historyResultFromAutosyncStatus(entry.status),
3011
3011
  sections: entry.appliedSections ?? [],
3012
3012
  source: 'autosync',
3013
3013
  summary: engineMsg('host.autosyncSummary', {
@@ -544,6 +544,29 @@ test('push 被远端推进检测拒绝(conflict)→ skipped(conflict) 而非
544
544
  );
545
545
  });
546
546
 
547
+ test('0.4.1 自愈:push 收养了本机残留基线(adoptedBase)→ success + 跳过码 baseline-adopted(面板能看见基线自己动过)', async () => {
548
+ const cfg: AutosyncConfig = { enabled: true, interval: '30m', startupMinIntervalMs: 300000, consecutiveFailures: 3 };
549
+ const engine = {
550
+ hasNewRemoteSnapshot: async () => false,
551
+ hasLocalChanges: async () => true,
552
+ push: async () => ({
553
+ ok: true, snapshotId: 'snap-healed', sections: [] as never,
554
+ warnings: ['远端最新快照 sync-001 是本机上次推送的:已收养为基线'],
555
+ adoptedBase: 'sync-001',
556
+ }),
557
+ };
558
+ const { scheduler, getConfig, getEntries } = makeScheduler({ cfg, engine, history: [] });
559
+ const result = await scheduler.runOnce('git');
560
+ assert.equal(result.status, 'success', '收养后照常推送 = 成功,不是跳过也不是失败');
561
+ assert.equal(result.skipReason, 'baseline-adopted', '要有独立跳过码,否则既有的「跳过」看不出为什么');
562
+ assert.equal(result.consecutiveFailures, 0, '自愈成功即归零连续失败');
563
+ assert.equal(getConfig().lastRunSkipReason, 'baseline-adopted');
564
+ assert.ok(
565
+ getEntries().some((e) => e.status === 'success' && e.skipReason === 'baseline-adopted'),
566
+ '历史必须留痕:不然用户看到基线跳变却查不到原因',
567
+ );
568
+ });
569
+
547
570
  test('runOnce: 无冲突且无变化 → success(pull,unchanged),不上传(本地也无改动)', async () => {
548
571
  const cfg: AutosyncConfig = { enabled: true, interval: '30m', startupMinIntervalMs: 300000, consecutiveFailures: 0 };
549
572
  const engine = {
@@ -883,11 +883,15 @@ export class AutoSyncScheduler {
883
883
  : partial
884
884
  ? conflictedSections
885
885
  : deferredSections;
886
+ // 0.4.1:推送前收养了「本机自己推上去的」远端快照(上次推送在写基线前被打断)→
887
+ // 如实记一条 skipReason,让历史与首页能说清「这次推上去之前先修好了基线」,
888
+ // 而不是让用户以为又发生了一次莫名冲突。冲突原因优先(真有冲突时更该被看见)。
889
+ const adoptedReason = pushReport.adoptedBase !== undefined ? ('baseline-adopted' as const) : undefined;
886
890
  const result: AutosyncRunResult = {
887
891
  status: partial ? 'partial' : 'success',
888
892
  direction: appliedSections.length ? 'both' : 'push',
889
893
  appliedSections, pushedSnapshotId: pushReport.snapshotId, historyId,
890
- ...(skipReason !== undefined ? { skipReason } : {}),
894
+ ...(skipReason !== undefined || adoptedReason !== undefined ? { skipReason: skipReason ?? adoptedReason } : {}),
891
895
  ...(reportedConflicted.length > 0 ? { conflictedSections: reportedConflicted } : {}),
892
896
  consecutiveFailures: 0,
893
897
  ...forcedMark,
@@ -896,7 +900,7 @@ export class AutoSyncScheduler {
896
900
  direction: appliedSections.length ? 'both' : 'push',
897
901
  status: partial ? 'partial' : 'success',
898
902
  appliedSections, pushedSnapshotId: pushReport.snapshotId,
899
- ...(skipReason !== undefined ? { skipReason } : {}),
903
+ ...(skipReason !== undefined || adoptedReason !== undefined ? { skipReason: skipReason ?? adoptedReason } : {}),
900
904
  ...(reportedConflicted.length > 0 ? { conflictedSections: reportedConflicted } : {}),
901
905
  createdAt: nowIso, failureCountAtRun: 0,
902
906
  ...forcedMark,
@@ -0,0 +1,74 @@
1
+ /**
2
+ * m-sync-flow:推送基线自愈(0.4.1)。
3
+ *
4
+ * 为什么单独成模块:这段逻辑是「事故形态 → 判据 → 只写 sync-state」的完整决策,
5
+ * 塞在 SyncEngine.push 里会让本就偏大的引擎再涨几十行(体量棘轮),而它本身不需要引擎的
6
+ * 任何其他状态 —— 只吃 (sync-state 目录, 快照元信息, 本机身份)。
7
+ *
8
+ * 事故形态(0.3.0 真机):push 在「transport.upload 成功」与「recordBaseline 写 sync-state」
9
+ * 之间被打断(退出/崩溃/断电/进程被杀)。远端已经前进、本机基线仍停在上一版,于是后续每一轮
10
+ * 前置推进检测都判定「远端被别的设备推进了」并拒绝推送 —— 用户被**自己推上去的快照**永久锁死,
11
+ * 只能手改 sync-state.json 才能解开。
12
+ *
13
+ * 判据只有一条:远端最新那份快照的 manifest.deviceId == 本机 deviceId。别的设备推进过、
14
+ * 或旧快照没记 deviceId(可能是任何机器)一律不收养,调用方仍按冲突返回 —— 绝不越过别人的改动。
15
+ */
16
+ import type { SectionId } from '../schema/types.ts';
17
+ import type { MsgFunc } from '../core/messages.ts';
18
+ import { joinFs } from './fs.ts';
19
+ import type { SnapshotFs } from './fs.ts';
20
+ import { loadSyncState, resolveDeviceIdentity, saveSyncState } from './sync-state.ts';
21
+ import type { SyncSnapshotMeta } from './transport.ts';
22
+
23
+ export interface AdoptOwnRemoteHeadOptions {
24
+ /** sync-state.json 所在目录。 */
25
+ stateDir: string;
26
+ fsx: SnapshotFs;
27
+ /** 本地快照副本目录(祖先来源);缺省 = 本机没有副本可指。 */
28
+ localSnapshotsDir?: string;
29
+ /** 远端快照列表(已按 createdAt 升序)。 */
30
+ metas: readonly SyncSnapshotMeta[];
31
+ /** 判定为「比基线新」的那份远端快照 id。 */
32
+ remoteId: string;
33
+ /** 本机当前基线(仅用于告警文案)。 */
34
+ base: string;
35
+ /** 本次通道身份(写回 sync-state.transport)。 */
36
+ transport: { type: string; ref: string };
37
+ hostname: string;
38
+ msg: MsgFunc;
39
+ /** 出参:收养说明追加到这里(调用方原样带给用户)。 */
40
+ warnings: string[];
41
+ }
42
+
43
+ /**
44
+ * 把「本机自己推上去、但基线没跟上」的远端最新快照收养为基线。
45
+ *
46
+ * 只写 sync-state:lastSnapshotId / 每分区 hash(取**被收养快照自己**的 sectionHashes,
47
+ * 不是本次导出结果)/ 祖先目录名(本机真有该副本才指过去,没有就保持原祖先 —— 三方合并仍成立,
48
+ * 也不会被写成一个不存在的目录名)。
49
+ *
50
+ * @returns 被收养的快照 id;null = 不满足收养条件(调用方按冲突返回)
51
+ */
52
+ export async function adoptOwnRemoteHead(opts: AdoptOwnRemoteHeadOptions): Promise<string | null> {
53
+ const meta = opts.metas.find((m) => m.id === opts.remoteId);
54
+ if (meta === undefined) return null;
55
+ const device = await resolveDeviceIdentity(opts.stateDir, opts.hostname, opts.fsx, opts.msg);
56
+ const remoteDevice = meta.manifest.deviceId;
57
+ if (typeof remoteDevice !== 'string' || remoteDevice === '' || remoteDevice !== device.id) return null;
58
+ const ancestorKnown = opts.localSnapshotsDir !== undefined
59
+ && await opts.fsx.isDir(joinFs(opts.localSnapshotsDir, opts.remoteId));
60
+ const state = await loadSyncState(opts.stateDir, opts.fsx, opts.msg);
61
+ state.lastSnapshotId = opts.remoteId;
62
+ if (ancestorKnown) state.ancestorId = opts.remoteId;
63
+ for (const [sid, hash] of Object.entries(meta.sections)) {
64
+ if (typeof hash !== 'string' || hash === '') continue;
65
+ state.sections[sid as SectionId] = { hash, updatedAt: meta.createdAt };
66
+ }
67
+ state.transport = opts.transport;
68
+ await saveSyncState(opts.stateDir, state, opts.fsx);
69
+ opts.warnings.push(opts.msg(ancestorKnown ? 'sync.pushBaselineAdopted' : 'sync.pushBaselineAdoptedNoAncestor', {
70
+ remote: opts.remoteId,
71
+ base: opts.base,
72
+ }));
73
+ return opts.remoteId;
74
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * push 前置:远端是否已被别的设备推进,以及「是本机自己推的」时收养基线(0.4.1)。
3
+ *
4
+ * 为什么单独成模块:这段判据是「推不推得上去」的唯一闸门,逻辑上只有三条出口
5
+ * (放行 / 告警放行 / 冲突拒绝),却要在 push 里挤掉二十多行 —— 抽出来后
6
+ * `sync-engine.push` 只剩「问一次闸门,拿到基线或冲突文案」。
7
+ *
8
+ * 事故形态(0.3.0 真机):transport.upload 已成功、recordBaseline 未执行 ⇒ 远端最新快照
9
+ * 就是本机自己那份,而基线还停在旧 id ⇒ 之后每轮都被判「远端被别的设备推进」永久拒绝,
10
+ * 每 60 s 一条失败,用户只能手改 sync-state。判据见 baseline-heal.ts:只有 deviceId 对得上
11
+ * 本机才收养,别的设备(或没有 deviceId 的旧快照)一律照旧拒绝。
12
+ */
13
+ import os from 'node:os';
14
+ import { adoptOwnRemoteHead } from './baseline-heal.ts';
15
+ import type { SnapshotFs } from './fs.ts';
16
+ import type { RemoteSnapshotIndex } from './session-tombstones.ts';
17
+ import { loadSyncState } from './sync-state.ts';
18
+ import type { SyncTransport } from './transport.ts';
19
+ import type { MsgFunc } from '../core/messages.ts';
20
+
21
+ export interface PushBaseOptions {
22
+ stateDir: string;
23
+ fsx: SnapshotFs;
24
+ localSnapshotsDir?: string;
25
+ /** SYN-02:本轮已列过的远端 index(推进检测与墓碑继承共用同一份)。 */
26
+ index: RemoteSnapshotIndex;
27
+ transport: Pick<SyncTransport, 'type'> & { ref: string };
28
+ hostname?: string;
29
+ msg: MsgFunc;
30
+ warnings: string[];
31
+ }
32
+
33
+ export type PushBaseOutcome =
34
+ | { ok: true; base: string; adopted?: string }
35
+ | { ok: false; message: string };
36
+
37
+ /**
38
+ * 判定本机能否继续推送,返回可用的基线。
39
+ *
40
+ * - 首次同步(没有基线)→ 放行;远端为空 → 放行(没有可比对的快照)。
41
+ * - 读不到远端列表 → **告警放行**(上传本身会再暴露通道问题),绝不把「读不到」当「没变」。
42
+ * - 远端最新快照就是当前基线 → 放行。
43
+ * - 远端最新快照是本机自己推的 → 收养为基线后放行(`adopted` 回传,调用方写进报告)。
44
+ * - 其余(别的设备的改动 / 没有 deviceId 的旧快照)→ 冲突拒绝,给 force 出口。
45
+ */
46
+ export async function resolvePushBase(opts: PushBaseOptions): Promise<PushBaseOutcome> {
47
+ const state = await loadSyncState(opts.stateDir, opts.fsx, opts.msg);
48
+ const base = state.lastSnapshotId;
49
+ if (base === '') return { ok: true, base };
50
+ if (opts.index.reason !== undefined) {
51
+ opts.warnings.push(opts.msg('sync.pushAdvanceCheckFailed', { reason: opts.index.reason }));
52
+ return { ok: true, base };
53
+ }
54
+ const metas = opts.index.metas;
55
+ if (metas.length === 0) return { ok: true, base };
56
+ const latest = metas[metas.length - 1]!.id; // list 按 createdAt 升序 → 最新在末
57
+ if (latest === base) return { ok: true, base };
58
+ const adopted = await adoptOwnRemoteHead({
59
+ stateDir: opts.stateDir,
60
+ fsx: opts.fsx,
61
+ localSnapshotsDir: opts.localSnapshotsDir,
62
+ metas,
63
+ remoteId: latest,
64
+ base,
65
+ transport: opts.transport,
66
+ hostname: opts.hostname ?? os.hostname(),
67
+ msg: opts.msg,
68
+ warnings: opts.warnings,
69
+ });
70
+ if (adopted === null) {
71
+ // 无法安全断言「远端没变」时的保守拒绝:不 upload、不记基线、不改 sync-state。
72
+ return { ok: false, message: opts.msg('sync.pushRemoteAdvanced', { remote: latest, base }) };
73
+ }
74
+ return { ok: true, base: adopted, adopted };
75
+ }
@@ -2635,6 +2635,94 @@ test('push: 远端列表读不出来 → 无法判定,按原样继续但如实
2635
2635
  }
2636
2636
  });
2637
2637
 
2638
+ /* ---------- 0.4.1 自愈:远端最新是「本机自己推的」快照时收养基线,不再永久互锁 ---------- */
2639
+
2640
+ test('push: 远端最新是本机自推的快照但基线没跟上(上传后、写基线前被打断)→ 收养为基线并继续推送', async () => {
2641
+ const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-push-adopt-own-'));
2642
+ try {
2643
+ const ctx = makeContext('win32', 'C:\\Users\\alice');
2644
+ seedSource(ctx);
2645
+ const transport = new MemSyncTransport();
2646
+ const engine = makeEngine({ ctx, transport, stateDir: tmp, localSnapshotsDir: path.join(tmp, 'anc') });
2647
+ assert.equal((await engine.push({ snapshotId: 'sync-001' })).ok, true);
2648
+ const ownId = transport.metas.at(-1)!.manifest.deviceId;
2649
+ assert.ok(typeof ownId === 'string' && ownId !== '', '快照必须带本机 deviceId(否则无从判定「这是我自己推的」)');
2650
+
2651
+ // 复现事故形态:上传已落地、sync-state 的基线指针仍停在更早的值
2652
+ await saveSyncState(tmp, {
2653
+ ...(await loadSyncState(tmp)),
2654
+ lastSnapshotId: 'sync-000',
2655
+ ancestorId: '',
2656
+ });
2657
+ transport.calls.length = 0;
2658
+
2659
+ const report = await engine.push({ snapshotId: 'sync-002' });
2660
+ assert.equal(report.ok, true, '本机自己的快照绝不把自己永久锁死: ' + (report.message ?? ''));
2661
+ assert.equal(report.adoptedBase, 'sync-001', '报告点明被收养的基线');
2662
+ assert.ok(
2663
+ report.warnings.some((w) => w.includes('sync-001')),
2664
+ '必须如实说明已收养(用户要知道基线自己动了): ' + report.warnings.join(' | '),
2665
+ );
2666
+ assert.equal(transport.snapshots.has('sync-002'), true, '收养后照常上传本次快照');
2667
+ const after = await loadSyncState(tmp);
2668
+ assert.equal(after.lastSnapshotId, 'sync-002', '基线推进到本次推送');
2669
+ assert.equal(after.ancestorId, 'sync-002', '本地有该收养快照的副本 → 祖先指针跟上(三方合并不降级)');
2670
+ } finally {
2671
+ await fs.rm(tmp, { recursive: true, force: true });
2672
+ }
2673
+ });
2674
+
2675
+ test('push: 远端最新是别的设备推的(deviceId 不同)→ 仍判冲突,零改写 sync-state', async () => {
2676
+ const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-push-adopt-other-'));
2677
+ try {
2678
+ const ctx = makeContext('win32', 'C:\\Users\\alice');
2679
+ seedSource(ctx);
2680
+ const transport = new MemSyncTransport();
2681
+ const engine = makeEngine({ ctx, transport, stateDir: tmp, localSnapshotsDir: path.join(tmp, 'anc') });
2682
+ assert.equal((await engine.push({ snapshotId: 'sync-base' })).ok, true);
2683
+ const stateBefore = await fs.readFile(path.join(tmp, SYNC_STATE_FILE), 'utf8');
2684
+
2685
+ const other = remoteSettingsSnapshot('sync-other', 'light', 5);
2686
+ other.manifest.deviceId = 'device-of-bob';
2687
+ seedRemoteSnapshot(transport, other);
2688
+ transport.calls.length = 0;
2689
+
2690
+ const refused = await engine.push({ snapshotId: 'sync-mine' });
2691
+ assert.equal(refused.ok, false, '别人推的绝不收养(那是要合并的改动,不是本机残留)');
2692
+ assert.equal(refused.conflict, true);
2693
+ assert.equal(refused.adoptedBase, undefined, '非本机快照不得给出 adoptedBase');
2694
+ assert.ok(!transport.calls.includes('upload'), '绝不 upload: ' + transport.calls.join(','));
2695
+ assert.equal(await fs.readFile(path.join(tmp, SYNC_STATE_FILE), 'utf8'), stateBefore, 'sync-state 逐字节不变');
2696
+ } finally {
2697
+ await fs.rm(tmp, { recursive: true, force: true });
2698
+ }
2699
+ });
2700
+
2701
+ test('push: 远端最新是旧快照(无 deviceId)→ 不猜,仍判冲突(旧快照可能来自任何机器)', async () => {
2702
+ const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-push-adopt-legacy-'));
2703
+ try {
2704
+ const ctx = makeContext('win32', 'C:\\Users\\alice');
2705
+ seedSource(ctx);
2706
+ const transport = new MemSyncTransport();
2707
+ const engine = makeEngine({ ctx, transport, stateDir: tmp, localSnapshotsDir: path.join(tmp, 'anc') });
2708
+ assert.equal((await engine.push({ snapshotId: 'sync-base' })).ok, true);
2709
+ const stateBefore = await fs.readFile(path.join(tmp, SYNC_STATE_FILE), 'utf8');
2710
+
2711
+ const legacy = remoteSettingsSnapshot('sync-legacy', 'light', 5);
2712
+ assert.equal(legacy.manifest.deviceId, undefined, '夹具就是「没记 deviceId」的旧快照');
2713
+ seedRemoteSnapshot(transport, legacy);
2714
+ transport.calls.length = 0;
2715
+
2716
+ const refused = await engine.push({ snapshotId: 'sync-mine' });
2717
+ assert.equal(refused.ok, false, '缺 deviceId → 不能证明是本机推的 → 不收养');
2718
+ assert.equal(refused.conflict, true);
2719
+ assert.ok(!transport.calls.includes('upload'));
2720
+ assert.equal(await fs.readFile(path.join(tmp, SYNC_STATE_FILE), 'utf8'), stateBefore, 'sync-state 逐字节不变');
2721
+ } finally {
2722
+ await fs.rm(tmp, { recursive: true, force: true });
2723
+ }
2724
+ });
2725
+
2638
2726
  test('previewMerge: 只读零写入 + 决策/计数/三侧预览(敏感值必须已脱敏)', async () => {
2639
2727
  const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-preview-merge-'));
2640
2728
  try {
@@ -41,6 +41,7 @@ import type { ZipWriteEntry } from '../utils/zip.ts';
41
41
  import { createSnapshotFs, joinFs } from './fs.ts';
42
42
  import type { SnapshotFs } from './fs.ts';
43
43
  import { writeSnapshotToDir } from './layout.ts';
44
+ import { resolvePushBase } from './push-precheck.ts';
44
45
  import {
45
46
  credentialsMapFromYaml, decryptCredentialsPayload, decryptSectionsPayload,
46
47
  encryptCredentialsPayload, encryptSectionsPayload,
@@ -49,7 +50,7 @@ import { OPT_IN_SYNC_SECTIONS } from './sync-selection.ts';
49
50
  import {
50
51
  listRemoteSnapshotIndex, planSessionBookkeeping, remoteTombstonesOf, stripTombstonedSessionsInPlace,
51
52
  } from './session-tombstones.ts';
52
- import type { RemoteSnapshotIndex, SessionBookkeepingResult } from './session-tombstones.ts';
53
+ import type { SessionBookkeepingResult } from './session-tombstones.ts';
53
54
  import { DEFAULT_RETENTION_POLICY, selectPruneCandidatesByPolicy } from './retention-policy.ts';
54
55
  import type { RetentionPolicy } from './retention-policy.ts';
55
56
  import { hashSection, loadSyncState, resolveDeviceIdentity, saveSyncState } from './sync-state.ts';
@@ -88,6 +89,8 @@ const zh = {
88
89
  'sync.applyMergeResolutionsNoImporter': 'applyMergeResolutions: SyncEngine 缺少 importer(需在 options 中注入)',
89
90
  'sync.mergePendingConflicts': '仍有 {count} 个分区未裁决({sections}):已裁决的部分已写入本机,但基线不推进,冲突下一轮会重新出现',
90
91
  'sync.baselineRexportFailed': '写回成功但重新导出本机分区失败({sections}):无法证明基线与本机一致,本次**不记基线**(远端指针保持原值,下一轮重新合并收敛)',
92
+ 'sync.pushBaselineAdopted': '远端最新快照 {remote} 是本机上次推送的(本机基线停在 {base},上次推送在记录基线前被打断):已把它收养为基线并继续本次推送',
93
+ 'sync.pushBaselineAdoptedNoAncestor': '远端最新快照 {remote} 是本机上次推送的,但本机没有它的本地祖先副本:已收养基线(下次合并退化为两方合并,结果仍安全)',
91
94
  } as const;
92
95
 
93
96
  const en: Record<keyof typeof zh, string> = {
@@ -97,6 +100,8 @@ const en: Record<keyof typeof zh, string> = {
97
100
  'sync.applyMergeResolutionsNoImporter': 'applyMergeResolutions: SyncEngine is missing the importer (must be injected via options)',
98
101
  'sync.mergePendingConflicts': '{count} section(s) still have no decision ({sections}): the decided parts were written locally, but the baseline is not advanced, so the conflicts will reappear next round',
99
102
  'sync.baselineRexportFailed': 'The write succeeded but re-exporting the local section(s) failed ({sections}): the baseline cannot be proven to match this machine, so no baseline was recorded (the remote pointer keeps its old value and the next merge converges again)',
103
+ 'sync.pushBaselineAdopted': 'The newest remote snapshot {remote} was pushed by this device (its baseline stopped at {base}: that push was interrupted before recording the baseline): the baseline has been adopted and this push continues',
104
+ 'sync.pushBaselineAdoptedNoAncestor': 'The newest remote snapshot {remote} was pushed by this device, but no local ancestor copy exists for it: the baseline has been adopted (the next merge degrades to a two-way merge, which is still safe)',
100
105
  };
101
106
 
102
107
  registerMessageCatalog({ id: 'sync-engine-merge', zh, en });
@@ -248,6 +253,15 @@ export interface SyncPushReport {
248
253
  * 而不是记成「同步失败」。
249
254
  */
250
255
  conflict?: boolean;
256
+ /**
257
+ * 本次推送前**收养了本机自己推上去的远端最新快照**(0.4.1 自愈):该值 = 被收养的快照 id。
258
+ *
259
+ * 触发场景:上次推送在上传成功、写基线之前被打断(进程退出/崩溃/断电),远端已前进而本机
260
+ * `lastSnapshotId` 仍是上一版 → 前置检测会永久拒绝推送(每次都说「远端被别人推进了」),
261
+ * 单设备用户因此被自己的快照锁死。判据只看「远端最新快照的 manifest.deviceId == 本机
262
+ * deviceId」,别的设备推进过就仍然按冲突返回,绝不越过。
263
+ */
264
+ adoptedBase?: string;
251
265
  }
252
266
 
253
267
  /** 差异报告中的单个变更项(PlanItem 摘要,不含敏感细节) */
@@ -843,6 +857,8 @@ export class SyncEngine {
843
857
  */
844
858
  async push(opts: SyncPushOptions = {}): Promise<SyncPushReport> {
845
859
  const warnings: string[] = [];
860
+ /** 0.4.1:本次推送前收养的「本机自己推的」远端快照(非空 ⇒ 上次推送被打断过,已在报告里如实回传) */
861
+ let adopted: string | undefined;
846
862
  const includeSecrets = opts.includeSecrets ?? false;
847
863
  const encrypt = opts.encrypt ?? false;
848
864
  // 安全不变量:导出密钥必须加密;加密必须给密码(密码绝不落盘)
@@ -855,23 +871,16 @@ export class SyncEngine {
855
871
  // SYN-02:本轮只列一次远端 index(推进检测 + 继承会话删除墓碑共用;墓碑累积在最新快照里)
856
872
  const remoteIndex = await listRemoteSnapshotIndex(this.transport);
857
873
  const remoteTombstones = remoteIndex.reason === undefined ? remoteTombstonesOf(remoteIndex.metas) : [];
858
- // 远端推进检测:不一致 = 远端被别的设备推过(或本机基线已被裁剪)。
859
- // 此时推上去会覆盖/架空别人的改动 → 直接返回冲突(**不抛错**、不 upload、不记基线、不改 sync-state)。
874
+ // 远端推进检测(判据与 0.4.1 自愈收养全在 push-precheck.ts);冲突时**不抛错**、
875
+ // 不 upload、不记基线、不改 sync-state,只把文案回给调用方走 force 出口。
860
876
  if (opts.force !== true) {
861
- const check = await this.remoteAdvancedCheck(remoteIndex);
862
- if (check.reason !== undefined) {
863
- // 读不到远端列表 ⇒ 无法判定。按原样继续(上传本身会再暴露通道问题),但如实说明。
864
- warnings.push(this.msg('sync.pushAdvanceCheckFailed', { reason: check.reason }));
865
- } else if (check.blocked) {
866
- return {
867
- ok: false,
868
- snapshotId: '',
869
- sections: [],
870
- warnings,
871
- conflict: true,
872
- message: this.msg('sync.pushRemoteAdvanced', { remote: check.latest, base: check.base }),
873
- };
874
- }
877
+ const pre = await resolvePushBase({
878
+ stateDir: this.stateDir, fsx: this.fsx, localSnapshotsDir: this.localSnapshotsDir,
879
+ index: remoteIndex, transport: { type: this.transport.type, ref: this.transportRef },
880
+ msg: this.msg, warnings,
881
+ });
882
+ if (!pre.ok) return { ok: false, snapshotId: '', sections: [], warnings, conflict: true, message: pre.message };
883
+ adopted = pre.adopted;
875
884
  }
876
885
  const plainSections: Partial<Record<SectionId, SectionData>> = {};
877
886
  const targets = this.pushTargets(opts.sections, warnings);
@@ -977,7 +986,13 @@ export class SyncEngine {
977
986
  : {}),
978
987
  });
979
988
 
980
- return { ok: true, snapshotId: id, sections: Object.keys(plainSections) as SectionId[], warnings };
989
+ return {
990
+ ok: true,
991
+ snapshotId: id,
992
+ sections: Object.keys(plainSections) as SectionId[],
993
+ warnings,
994
+ ...(adopted !== undefined ? { adoptedBase: adopted } : {}),
995
+ };
981
996
  }
982
997
 
983
998
  /**
@@ -1185,31 +1200,6 @@ export class SyncEngine {
1185
1200
  }
1186
1201
  }
1187
1202
 
1188
- /**
1189
- * push 前置:远端是否已被别的设备推进(防「推上去把别人的改动架空」)。
1190
- *
1191
- * 判据与 hasNewRemoteSnapshot() 同源但方向相反:
1192
- * - 首次同步(lastSnapshotId === '')→ **不拦**(本机没有基线可丢,第一次推送就是建立基线);
1193
- * - 远端为空 → 不拦(没有可比对的快照);
1194
- * - 其余:远端最新快照 id !== lastSnapshotId ⇒ 远端被推进(或本机基线已被裁剪)→ 拦。
1195
- * 两种情况都**无法安全断言「远端没变」**,保守拒绝并给出 force 出口。
1196
- * - list() 抛错 → 返回 reason(调用方按原样继续并告警),绝不把「读不到」当成「没变」。
1197
- * - SYN-02:index 可由 push() 传入(同一轮只列一次远端),缺省自己 list(其它调用点行为不变)。
1198
- */
1199
- private async remoteAdvancedCheck(
1200
- index?: RemoteSnapshotIndex,
1201
- ): Promise<{ blocked: boolean; base: string; latest: string; reason?: string }> {
1202
- const state = await loadSyncState(this.stateDir, this.fsx, this.msg);
1203
- const base = state.lastSnapshotId;
1204
- if (base === '') return { blocked: false, base, latest: '' };
1205
- const listed = index ?? await listRemoteSnapshotIndex(this.transport);
1206
- if (listed.reason !== undefined) return { blocked: false, base, latest: '', reason: listed.reason };
1207
- const metas = listed.metas;
1208
- if (metas.length === 0) return { blocked: false, base, latest: '' };
1209
- const latest = metas[metas.length - 1]!.id; // list 按 createdAt 升序 → 最新在末
1210
- return { blocked: latest !== base, base, latest };
1211
- }
1212
-
1213
1203
  /**
1214
1204
  * pull:拉取远端最新(或指定)快照 → 过滤 portable 分区 → 转临时标准 ZIP →
1215
1205
  * 复用 Importer 预览流程(analyzeImport/createImportPlan)产出差异报告。
@@ -56,7 +56,8 @@ test('HISTORY_KIND_OPTIONS:恰为 §5 全清单(含 profile-import)', () =
56
56
  'sync-apply', 'autosync', 'recovery',
57
57
  'backup', 'backup-manual', 'snapshot-delete', 'snapshot-prune',
58
58
  ]);
59
- assert.deepEqual(HISTORY_RESULT_OPTIONS, ['success', 'failed', 'skipped']);
59
+ // pending(待裁决)排在 skipped 之前:它需要用户动手,比「跳过」更该先看到。
60
+ assert.deepEqual(HISTORY_RESULT_OPTIONS, ['success', 'pending', 'skipped', 'failed']);
60
61
  });
61
62
 
62
63
  test('groupByKind:空组不渲染、组内按时间倒序、顺序保持清单序', () => {
@@ -15,7 +15,8 @@ import type { MigrationKind, MigrationResult, StoredMigrationHistoryEntry } from
15
15
  export function resultBadgeKind(result: MigrationResult): 'ok' | 'error' | 'warn' | 'info' {
16
16
  if (result === 'success') return 'ok';
17
17
  if (result === 'failed') return 'error';
18
- return 'warn'; // skipped
18
+ // pending(0.4.1)= 跑完了但还有待裁决项:绝不当成失败(红),也不是跳过 —— 用琥珀告警色
19
+ return 'warn'; // skipped / pending
19
20
  }
20
21
 
21
22
  /** kind 标签(本地化 key 基名;i18n 字典用 `history.kind.<kind>` 渲染)。 */
@@ -34,7 +35,7 @@ export const HISTORY_KIND_OPTIONS: readonly MigrationKind[] = [
34
35
  ] as const;
35
36
 
36
37
  /** 结果过滤选项。 */
37
- export const HISTORY_RESULT_OPTIONS: readonly MigrationResult[] = ['success', 'failed', 'skipped'] as const;
38
+ export const HISTORY_RESULT_OPTIONS: readonly MigrationResult[] = ['success', 'pending', 'skipped', 'failed'] as const;
38
39
 
39
40
  /** 过滤模型(UI 状态;空 = 不过滤)。 */
40
41
  export interface HistoryFilter {
@@ -183,6 +183,18 @@ test('overviewActivity: 倒序 + limit + 徽章语义 + kind key 归一', () =>
183
183
  assert.equal(overviewActivity([]).length, 0)
184
184
  })
185
185
 
186
+ test('overviewActivity: result=pending(跑完但仍有待裁决)→ badge pending,既不红成失败也不混进跳过', () => {
187
+ const items = overviewActivity([
188
+ { at: '2026-09-01T00:00:00Z', kind: 'autosync', result: 'pending', summary: '自动同步有冲突待裁决' },
189
+ { at: '2026-09-02T00:00:00Z', kind: 'autosync', result: 'skipped', summary: '跳过' },
190
+ { at: '2026-09-03T00:00:00Z', kind: 'autosync', result: 'failed', summary: '失败' },
191
+ ])
192
+ const bySummary = (s: string) => items.find((i) => i.summary === s)!
193
+ assert.equal(bySummary('自动同步有冲突待裁决').badge, 'pending')
194
+ assert.equal(bySummary('跳过').badge, 'warn', 'skipped 仍是 warn —— 两种语义不能合并')
195
+ assert.equal(bySummary('失败').badge, 'error')
196
+ })
197
+
186
198
  /* ---------------- 空态 ---------------- */
187
199
 
188
200
  test('overviewEmptyState: 备份与快照均加载且为空 → true', () => {