dsh-config-manager 0.3.1 → 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 (92) hide show
  1. package/lib/client.d.ts +54 -3
  2. package/lib/client.js +1078 -845
  3. package/lib/core/env-lock-lifecycle.d.ts +45 -0
  4. package/lib/core/env-lock-lifecycle.js +43 -0
  5. package/lib/core/history-prune.d.ts +34 -0
  6. package/lib/core/history-prune.js +43 -0
  7. package/lib/core/index.d.ts +1 -1
  8. package/lib/core/index.js +1 -1
  9. package/lib/core/messages-core.d.ts +1 -0
  10. package/lib/core/messages-core.js +2 -0
  11. package/lib/core/migration-history.d.ts +46 -4
  12. package/lib/core/migration-history.js +60 -7
  13. package/lib/index.d.ts +2 -2
  14. package/lib/index.js +26 -8
  15. package/lib/routes/history.js +70 -5
  16. package/lib/routes/index.d.ts +1 -1
  17. package/lib/routes/kit.d.ts +2 -2
  18. package/lib/routes/messages.d.ts +1 -0
  19. package/lib/routes/messages.js +3 -0
  20. package/lib/sync/autosync-scheduler.js +12 -2
  21. package/lib/sync/backup-scheduler.js +6 -0
  22. package/lib/sync/baseline-heal.d.ts +35 -0
  23. package/lib/sync/baseline-heal.js +39 -0
  24. package/lib/sync/push-precheck.d.ts +35 -0
  25. package/lib/sync/push-precheck.js +58 -0
  26. package/lib/sync/sync-engine.d.ts +9 -12
  27. package/lib/sync/sync-engine.js +24 -43
  28. package/lib/sync/ui-prefs.d.ts +8 -0
  29. package/lib/sync/ui-prefs.js +8 -0
  30. package/lib/ui/history-model.js +3 -2
  31. package/lib/ui/overview-view.d.ts +3 -3
  32. package/lib/ui/overview-view.js +9 -1
  33. package/lib/utils/env-lock.d.ts +55 -1
  34. package/lib/utils/env-lock.js +131 -2
  35. package/lib/utils/messages-utils.d.ts +3 -0
  36. package/lib/utils/messages-utils.js +6 -0
  37. package/package.json +1 -1
  38. package/src/client/common/InfoHint.tsx +12 -3
  39. package/src/client/common/Skeleton.tsx +45 -8
  40. package/src/client/common/info-hint-guard.test.ts +196 -0
  41. package/src/client/common/routes.ts +3 -1
  42. package/src/client/common/skeleton-guard.test.ts +58 -0
  43. package/src/client/common/ui.tsx +17 -4
  44. package/src/client/config-manager.module.css +256 -27
  45. package/src/client/css-motion-guard.test.ts +230 -0
  46. package/src/client/environment/EnvironmentPanel.tsx +41 -29
  47. package/src/client/environment/maintenance/DiskUsageCard.tsx +28 -33
  48. package/src/client/environment/profiles-incomplete-ui.test.ts +9 -5
  49. package/src/client/export/ExportView.tsx +6 -6
  50. package/src/client/history/HistoryPanel.tsx +87 -2
  51. package/src/client/history/history-api.ts +49 -3
  52. package/src/client/history/history-locales.ts +32 -0
  53. package/src/client/home/HomePanel.tsx +64 -26
  54. package/src/client/locales.ts +2 -0
  55. package/src/client/market/MyConfigsWizard.tsx +12 -3
  56. package/src/client/recovery/RecoveryPanel.tsx +93 -92
  57. package/src/client/recovery/RollbackCard.tsx +25 -16
  58. package/src/client/sync/AutosyncCard.tsx +12 -6
  59. package/src/client/sync/ChannelConfigDialog.tsx +45 -45
  60. package/src/client/sync/DecryptPasswordCard.tsx +3 -3
  61. package/src/client/sync/SecurityOptionsCard.tsx +3 -3
  62. package/src/client/sync/SyncSectionPickerDialog.tsx +3 -3
  63. package/src/client/sync/history-model.ts +3 -0
  64. package/src/client/sync/sync-locales.ts +2 -0
  65. package/src/core/env-lock-lifecycle.ts +73 -0
  66. package/src/core/history-prune.test.ts +115 -0
  67. package/src/core/history-prune.ts +61 -0
  68. package/src/core/index.ts +2 -0
  69. package/src/core/messages-core.ts +2 -0
  70. package/src/core/migration-history.test.ts +97 -0
  71. package/src/core/migration-history.ts +74 -9
  72. package/src/index.ts +27 -8
  73. package/src/routes/history.ts +81 -4
  74. package/src/routes/index.ts +1 -1
  75. package/src/routes/kit.ts +2 -2
  76. package/src/routes/messages.ts +3 -0
  77. package/src/sync/autosync-scheduler.test.ts +23 -0
  78. package/src/sync/autosync-scheduler.ts +9 -2
  79. package/src/sync/backup-scheduler.ts +3 -0
  80. package/src/sync/baseline-heal.ts +74 -0
  81. package/src/sync/push-precheck.ts +75 -0
  82. package/src/sync/sync-engine.test.ts +88 -0
  83. package/src/sync/sync-engine.ts +33 -43
  84. package/src/sync/ui-prefs.test.ts +32 -0
  85. package/src/sync/ui-prefs.ts +16 -0
  86. package/src/ui/history-model.test.ts +2 -1
  87. package/src/ui/history-model.ts +3 -2
  88. package/src/ui/overview-view.test.ts +12 -0
  89. package/src/ui/overview-view.ts +12 -4
  90. package/src/utils/env-lock.test.ts +107 -0
  91. package/src/utils/env-lock.ts +124 -2
  92. package/src/utils/messages-utils.ts +6 -0
@@ -5,28 +5,60 @@
5
5
  * path/methods 就是唯一声明处;围栏、方法判定与顶层异常处理由 src/routes/kit.ts 在注册点统一提供。
6
6
  */
7
7
 
8
- import { endpoint, writeJson } from './kit.ts'
8
+ import { endpoint, requireJsonObject, writeJson } from './kit.ts'
9
9
  import type { WebRoute } from './kit.ts'
10
10
  import type { RoutesEnv } from './context.ts'
11
- import { parseHistoryQuery, queryHistory, renderExport, summarizeHistory } from '../core/migration-history.ts'
11
+ import {
12
+ DEFAULT_MIGRATION_RETENTION,
13
+ HISTORY_RETENTION_MAX,
14
+ HISTORY_RETENTION_MIN,
15
+ isValidHistoryRetention,
16
+ parseHistoryQuery,
17
+ queryHistory,
18
+ renderExport,
19
+ resolveHistoryRetention,
20
+ summarizeHistory,
21
+ } from '../core/migration-history.ts'
22
+ import { readUiPrefs, updateUiPrefs } from '../sync/ui-prefs.ts'
23
+
24
+ /** 列表接口的 limit 上限:防「?limit=99999999」把只读端点的读放大成拒绝服务面。 */
25
+ const HISTORY_LIST_LIMIT_MAX = 5000
26
+
27
+ /**
28
+ * 解析列表请求的 limit:缺省 / 非法 / 负数 = 0(= 全量,老口径不变);超上限按上限截断。
29
+ * 只接受十进制整数字面量(parseInt 会把 '12abc' 读成 12,故先用正则判形)。
30
+ */
31
+ function parseListLimit(raw: string | null): number {
32
+ if (raw === null || !/^\d+$/.test(raw.trim())) return 0
33
+ const n = Number.parseInt(raw.trim(), 10)
34
+ if (!Number.isFinite(n) || n <= 0) return 0
35
+ return Math.min(n, HISTORY_LIST_LIMIT_MAX)
36
+ }
12
37
 
13
38
  export function historyRoutes(env: RoutesEnv): WebRoute[] {
14
39
  const {
15
40
  history,
16
41
  host,
42
+ msg,
43
+ syncDir,
44
+ withMutationGate,
17
45
  } = env
18
46
  return [
19
47
  // ------------------------------------------------------------ history
20
48
  // Phase 6:迁移历史审计(统一历史引擎)。只读 GET:列表(过滤)+ 导出。
21
49
  // loopback fence(guard)与全仓一致——仅同源 + loopback 可访问。
50
+ // ?limit=N:只读最近 N 条(文件名尾部窗口)。首页只要最近几十条活动,全量读 + 全量回传
51
+ // 会把首屏骨架拖到秒级(真机 2360 条:纯 IO/解析 650 ms,冷启动含回传 9.7 s)。
52
+ // 响应始终带 total(目录合法文件总数)与 scanned(本次实际读取条数),避免 UI 把窗口当全量。
22
53
  endpoint({ path: '/api/dsh-config-manager/history', methods: ['GET'] }, async (req, res) => {
23
54
  try {
24
55
  const url = new URL(req.url ?? '/', 'http://localhost')
25
56
  const q = parseHistoryQuery(Object.fromEntries(url.searchParams))
26
- const { entries, corrupted } = await history.read()
57
+ const limit = parseListLimit(url.searchParams.get('limit'))
58
+ const { entries, corrupted, total } = await history.read({ limit })
27
59
  const filtered = queryHistory(entries, q)
28
60
  const stats = summarizeHistory(filtered)
29
- writeJson(res, 200, { ok: true, entries: filtered, stats, corrupted })
61
+ writeJson(res, 200, { ok: true, entries: filtered, stats, corrupted, total: total ?? entries.length, scanned: entries.length, limit })
30
62
  } catch (error) {
31
63
  writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
32
64
  }
@@ -52,5 +84,50 @@ export function historyRoutes(env: RoutesEnv): WebRoute[] {
52
84
  writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
53
85
  }
54
86
  }),
87
+ // ------------------------------------------------------ history/retention
88
+ // 迁移历史自动清理(issue:历史目录只增不减,真机已 2360 条 / 0.67 MB)。
89
+ // 策略存 ui-prefs.json 的 historyRetentionMaxEntries(0 = 不限制,缺省 1000);
90
+ // 宿主在每次写入历史后按该值节流清理最旧条目(调度与取舍 → src/core/history-prune.ts)。
91
+ // GET → 当前策略 + 目录现状;POST → 改策略并立即清理一次(同一道写入门)。
92
+ // 一条 exact 路由 + 方法内部分发:webserver 对重复 (kind, path) 直接抛错。
93
+ endpoint({ path: '/api/dsh-config-manager/history/retention', methods: ['GET', 'POST'] }, async (req, res) => {
94
+ if (req.method === 'GET') {
95
+ try {
96
+ const [prefs, total] = await Promise.all([readUiPrefs(syncDir), history.count()])
97
+ writeJson(res, 200, {
98
+ ok: true,
99
+ maxEntries: resolveHistoryRetention(prefs.historyRetentionMaxEntries),
100
+ total,
101
+ defaultMaxEntries: DEFAULT_MIGRATION_RETENTION,
102
+ allowedMin: HISTORY_RETENTION_MIN,
103
+ allowedMax: HISTORY_RETENTION_MAX,
104
+ })
105
+ } catch (error) {
106
+ writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
107
+ }
108
+ return
109
+ }
110
+ // 写分支:删历史属破坏性操作,与其它写路径同一道门(不写审计条目 → 见 history-prune 头注释)。
111
+ await withMutationGate('history-retention', async (gatedReq, gatedRes) => {
112
+ const body = await requireJsonObject(gatedReq)
113
+ const next = body['maxEntries']
114
+ if (!isValidHistoryRetention(next)) {
115
+ writeJson(gatedRes, 400, {
116
+ ok: false,
117
+ code: 'invalid-retention',
118
+ error: msg('route.historyRetentionInvalid', { min: HISTORY_RETENTION_MIN, max: HISTORY_RETENTION_MAX }),
119
+ })
120
+ return
121
+ }
122
+ // 先落策略再清理:清理失败也要让新策略生效(下一次写入会重试),否则用户改完不生效。
123
+ await updateUiPrefs(syncDir, { historyRetentionMaxEntries: next })
124
+ const removed = next > 0 ? await history.retention(next) : []
125
+ const total = await history.count()
126
+ if (removed.length > 0) {
127
+ host.log.info('迁移历史自动清理', { maxEntries: next, removed: removed.length, total })
128
+ }
129
+ writeJson(gatedRes, 200, { ok: true, maxEntries: next, removed: removed.length, total })
130
+ }, { journaled: false })(req, res)
131
+ }),
55
132
  ]
56
133
  }
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * 顺序对匹配无影响:DSH webServer 的契约是「命名路由必须互不相同,注册顺序不影响请求」
5
5
  * (见 @deepseek-ai/dsh-host-webserver 的 WebServer 文档)。src/index.ts 保留的 7 条被源码级
6
- * 守卫按文件窗口钉住,其余 76 条在这里组装(总数 83:含 path-browse)。
6
+ * 守卫按文件窗口钉住,其余 77 条在这里组装(总数 84:含 path-browse)。
7
7
  */
8
8
  import type { WebRoute } from './kit.ts'
9
9
  import type { RoutesEnv } from './context.ts'
package/src/routes/kit.ts CHANGED
@@ -8,8 +8,8 @@
8
8
  * - 「每条路由首行 guard」这条安全不变量此前**只写在注释里**,零测试覆盖;
9
9
  * - 3 条 prefix 路由自造围栏(裸 isLoopbackRequest + 自判方法)。
10
10
  *
11
- * 计数口径(三路一致 = 83,勿再照抄旧审计初稿的计数 —— 那是计数口径 overcount):
12
- * 路由快照 83 条 = 现行 `endpoint()` 声明 83 条 = 运行期 `buildRoutes()` 76 条 + `src/index.ts` 保留的 7 条。
11
+ * 计数口径(三路一致 = 84,勿再照抄旧审计初稿的计数 —— 那是计数口径 overcount):
12
+ * 路由快照 84 条 = 现行 `endpoint()` 声明 84 条 = 运行期 `buildRoutes()` 77 条 + `src/index.ts` 保留的 7 条。
13
13
  * 增删路由后必须同步这段计数、`src/routes/index.ts` 的头注释与 parity 快照清单;`tests/route/route-parity.test.ts`
14
14
  * 的「路由计数散文」守卫会拿真实声明数逐条对账(写错即红灯)。
15
15
  *
@@ -23,6 +23,8 @@ export const zh = {
23
23
  'route.importNoSections': '无分区',
24
24
  'route.importHistorySummary': '导入完成:{sections}(执行 {count} 项)',
25
25
  'route.importIncomplete': '导入未完全成功',
26
+ // ---------- 迁移历史自动清理 ----------
27
+ 'route.historyRetentionInvalid': '保留上限必须是 {min}–{max} 之间的整数(0 = 不限制)',
26
28
  // ---------- 档案 ----------
27
29
  'route.profileLaunchSummary': '启动档案 {name}(独立实例 :{port})',
28
30
  'route.profileCreateSummary': '新建档案 {name}(模板 {template})',
@@ -67,6 +69,7 @@ export const en: Record<keyof typeof zh, string> = {
67
69
  'route.importNoSections': 'no sections',
68
70
  'route.importHistorySummary': 'Import finished: {sections} ({count} item(s) executed)',
69
71
  'route.importIncomplete': 'Import did not fully succeed',
72
+ 'route.historyRetentionInvalid': 'Retention limit must be an integer between {min} and {max} (0 = unlimited)',
70
73
  'route.profileLaunchSummary': 'Launched profile {name} (separate instance :{port})',
71
74
  'route.profileCreateSummary': 'Created profile {name} (template {template})',
72
75
  'route.profileCopySummary': 'Copied profile {from} → {to}{suffix}',
@@ -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 = {
@@ -577,6 +577,9 @@ export class AutoSyncScheduler {
577
577
  let releaseLock: (() => Promise<void>) | null = null;
578
578
  if (this.mutationLock !== undefined) {
579
579
  try {
580
+ // 本轮开始前先自愈:上一轮异常退出留下的**可证** stale 残留锁只会让每轮静默 skip,
581
+ // 用户不重启就永远不同步。只删可证的(owner 确证死亡 / PID 复用),其余保持下面既有的 warn 路径。
582
+ try { await this.mutationLock.reclaimProvableStaleLock?.() } catch { /* 预检失败不改变既有路径 */ }
580
583
  const lk = await withMutationLock(this.mutationLock, { op: 'autosync', target: channel, isBlocked: this.isBlocked });
581
584
  if (lk.context === null) {
582
585
  this.running = false;
@@ -880,11 +883,15 @@ export class AutoSyncScheduler {
880
883
  : partial
881
884
  ? conflictedSections
882
885
  : deferredSections;
886
+ // 0.4.1:推送前收养了「本机自己推上去的」远端快照(上次推送在写基线前被打断)→
887
+ // 如实记一条 skipReason,让历史与首页能说清「这次推上去之前先修好了基线」,
888
+ // 而不是让用户以为又发生了一次莫名冲突。冲突原因优先(真有冲突时更该被看见)。
889
+ const adoptedReason = pushReport.adoptedBase !== undefined ? ('baseline-adopted' as const) : undefined;
883
890
  const result: AutosyncRunResult = {
884
891
  status: partial ? 'partial' : 'success',
885
892
  direction: appliedSections.length ? 'both' : 'push',
886
893
  appliedSections, pushedSnapshotId: pushReport.snapshotId, historyId,
887
- ...(skipReason !== undefined ? { skipReason } : {}),
894
+ ...(skipReason !== undefined || adoptedReason !== undefined ? { skipReason: skipReason ?? adoptedReason } : {}),
888
895
  ...(reportedConflicted.length > 0 ? { conflictedSections: reportedConflicted } : {}),
889
896
  consecutiveFailures: 0,
890
897
  ...forcedMark,
@@ -893,7 +900,7 @@ export class AutoSyncScheduler {
893
900
  direction: appliedSections.length ? 'both' : 'push',
894
901
  status: partial ? 'partial' : 'success',
895
902
  appliedSections, pushedSnapshotId: pushReport.snapshotId,
896
- ...(skipReason !== undefined ? { skipReason } : {}),
903
+ ...(skipReason !== undefined || adoptedReason !== undefined ? { skipReason: skipReason ?? adoptedReason } : {}),
897
904
  ...(reportedConflicted.length > 0 ? { conflictedSections: reportedConflicted } : {}),
898
905
  createdAt: nowIso, failureCountAtRun: 0,
899
906
  ...forcedMark,
@@ -261,6 +261,9 @@ export class BackupScheduler {
261
261
  }
262
262
 
263
263
  try {
264
+ // 本轮开始前先自愈:可证的 stale 残留锁会让每轮备份直接 skipped,用户不重启就永远不备份。
265
+ // 只删可证的(owner 确证死亡 / PID 复用);不可证的仍走下面 runWithMutationLock 的 skipped 分支。
266
+ try { await this.mutationLock?.reclaimProvableStaleLock?.() } catch { /* 预检失败不改变既有路径 */ }
264
267
  // Phase 2 锁:定时备份写入 exports 属 GLOBAL mutation(与 Sync push / 手动备份互斥)。
265
268
  // 无锁环境(测试)→ 不锁定直接执行;锁被占用 → 返回 failed(destructive 不执行)。
266
269
  const result: BackupRunResult = await runWithMutationLock(this.mutationLock, { op: 'backup-schedule', target: 'exports', isBlocked: this.isBlocked }, async (lockCtx) => {
@@ -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)产出差异报告。