dsh-config-manager 0.4.0 → 0.4.2

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 (152) hide show
  1. package/lib/cli/actions.js +2 -3
  2. package/lib/cli/import-source.js +2 -6
  3. package/lib/cli/index.js +2 -3
  4. package/lib/client.d.ts +21 -7
  5. package/lib/client.js +26122 -25799
  6. package/lib/core/exporter.js +2 -4
  7. package/lib/core/host-schedulers/cache-cleanup.d.ts +41 -0
  8. package/lib/core/host-schedulers/cache-cleanup.js +45 -0
  9. package/lib/core/host-schedulers/lifecycle-hooks.d.ts +51 -0
  10. package/lib/core/host-schedulers/lifecycle-hooks.js +78 -0
  11. package/lib/core/host-schedulers/market-cache.d.ts +40 -0
  12. package/lib/core/host-schedulers/market-cache.js +92 -0
  13. package/lib/core/messages-core.d.ts +1 -0
  14. package/lib/core/messages-core.js +2 -0
  15. package/lib/core/migration-history.d.ts +18 -2
  16. package/lib/core/migration-history.js +19 -3
  17. package/lib/core/model-tools.js +2 -6
  18. package/lib/core/restore.d.ts +0 -2
  19. package/lib/core/restore.js +16 -18
  20. package/lib/core/verify-recovery.js +4 -7
  21. package/lib/index.d.ts +3 -22
  22. package/lib/index.js +71 -327
  23. package/lib/profiles/dsh-profile-manager.d.ts +23 -1
  24. package/lib/profiles/dsh-profile-manager.js +70 -2
  25. package/lib/routes/kit.d.ts +21 -0
  26. package/lib/routes/kit.js +29 -0
  27. package/lib/routes/prefs.js +6 -6
  28. package/lib/routes/recovery.js +25 -41
  29. package/lib/routes/route-support.d.ts +23 -1
  30. package/lib/routes/route-support.js +185 -0
  31. package/lib/routes/snapshots.js +4 -11
  32. package/lib/routes/sync.js +5 -7
  33. package/lib/security/redaction.d.ts +5 -1
  34. package/lib/security/redaction.js +26 -23
  35. package/lib/sync/autosync-scheduler.js +6 -2
  36. package/lib/sync/backup-scheduler.js +2 -6
  37. package/lib/sync/baseline-heal.d.ts +35 -0
  38. package/lib/sync/baseline-heal.js +39 -0
  39. package/lib/sync/push-precheck.d.ts +35 -0
  40. package/lib/sync/push-precheck.js +58 -0
  41. package/lib/sync/sync-engine.d.ts +9 -12
  42. package/lib/sync/sync-engine.js +24 -43
  43. package/lib/ui/backup-inspect.d.ts +1 -1
  44. package/lib/ui/dsh-profiles-view.d.ts +0 -10
  45. package/lib/ui/dsh-profiles-view.js +3 -7
  46. package/lib/ui/history-model.js +3 -2
  47. package/lib/ui/overview-view.d.ts +3 -3
  48. package/lib/ui/overview-view.js +9 -1
  49. package/lib/ui/snapshots-view.d.ts +0 -14
  50. package/lib/ui/snapshots-view.js +16 -2
  51. package/lib/utils/paths.d.ts +20 -4
  52. package/lib/utils/paths.js +22 -6
  53. package/lib/utils/time.d.ts +31 -0
  54. package/lib/utils/time.js +54 -0
  55. package/package.json +1 -1
  56. package/src/cli/actions.ts +2 -3
  57. package/src/cli/import-source.ts +2 -7
  58. package/src/cli/index.ts +2 -3
  59. package/src/client/about/AboutPanel.tsx +1 -1
  60. package/src/client/about/ReleaseBody.tsx +22 -52
  61. package/src/client/about/ReleaseNotesDialog.tsx +15 -69
  62. package/src/client/about/release-notes-view.ts +4 -11
  63. package/src/client/common/info-hint-guard.test.ts +11 -5
  64. package/src/client/common/ui.tsx +23 -0
  65. package/src/client/config-manager.module.css +201 -32
  66. package/src/client/css-token-guard.test.ts +135 -1
  67. package/src/client/history/history-locales.ts +2 -0
  68. package/src/client/home/HomePanel.tsx +9 -3
  69. package/src/client/import/ConflictList.tsx +3 -3
  70. package/src/client/import/ImportWizardView.tsx +1 -1
  71. package/src/client/library/ArtifactRow.tsx +2 -2
  72. package/src/client/library/RestorePlanView.tsx +21 -9
  73. package/src/client/library/report-dismiss.test.ts +5 -3
  74. package/src/client/locales/about.ts +97 -0
  75. package/src/client/locales/backup.ts +141 -0
  76. package/src/client/locales/common.ts +113 -0
  77. package/src/client/locales/export.ts +184 -0
  78. package/src/client/locales/foreign.ts +184 -0
  79. package/src/client/locales/import-compat.ts +32 -0
  80. package/src/client/locales/import.ts +192 -0
  81. package/src/client/locales/next-steps.ts +25 -0
  82. package/src/client/locales/overview-control.ts +32 -0
  83. package/src/client/locales/overview.ts +145 -0
  84. package/src/client/locales/profiles.ts +263 -0
  85. package/src/client/locales/report.ts +17 -0
  86. package/src/client/locales/restore.ts +132 -0
  87. package/src/client/locales/sessions.ts +257 -0
  88. package/src/client/locales/shell.ts +149 -0
  89. package/src/client/locales.ts +49 -1781
  90. package/src/client/market/MarketImportReview.tsx +2 -2
  91. package/src/client/market/MarketPanel.tsx +1 -1
  92. package/src/client/market/market-view.ts +3 -5
  93. package/src/client/recovery/RecoveryPanel.tsx +62 -1054
  94. package/src/client/recovery/SessionHealthCard.tsx +134 -0
  95. package/src/client/recovery/SessionHealthDialog.tsx +665 -0
  96. package/src/client/recovery/SessionLayoutSection.tsx +284 -0
  97. package/src/client/recovery/recovery-api.ts +10 -1
  98. package/src/client/recovery/recovery-panel-layout.test.ts +20 -5
  99. package/src/client/recovery/session-dialog-mount.test.ts +16 -9
  100. package/src/client/recovery/use-recovery-write.test.ts +90 -0
  101. package/src/client/recovery/use-recovery-write.ts +53 -0
  102. package/src/client/run-store.ts +57 -2
  103. package/src/client/sync/PushPreviewCard.tsx +2 -2
  104. package/src/client/sync/SyncConfirmView.tsx +5 -5
  105. package/src/client/sync/SyncLogList.tsx +2 -2
  106. package/src/client/sync/history-model.ts +7 -5
  107. package/src/client/sync/sync-locales.ts +2 -0
  108. package/src/client/sync/sync-view.ts +3 -4
  109. package/src/core/exporter.ts +2 -4
  110. package/src/core/host-schedulers/cache-cleanup.test.ts +84 -0
  111. package/src/core/host-schedulers/cache-cleanup.ts +74 -0
  112. package/src/core/host-schedulers/lifecycle-hooks.test.ts +111 -0
  113. package/src/core/host-schedulers/lifecycle-hooks.ts +118 -0
  114. package/src/core/host-schedulers/market-cache.test.ts +93 -0
  115. package/src/core/host-schedulers/market-cache.ts +116 -0
  116. package/src/core/messages-core.ts +2 -0
  117. package/src/core/migration-history.test.ts +19 -0
  118. package/src/core/migration-history.ts +28 -5
  119. package/src/core/model-tools.ts +2 -7
  120. package/src/core/restore-failure-state.test.ts +210 -0
  121. package/src/core/restore.ts +16 -18
  122. package/src/core/verify-recovery.ts +4 -7
  123. package/src/index.ts +78 -332
  124. package/src/profiles/dsh-profile-copy-rollback.test.ts +156 -0
  125. package/src/profiles/dsh-profile-manager.ts +71 -3
  126. package/src/routes/kit.ts +37 -0
  127. package/src/routes/prefs.ts +6 -6
  128. package/src/routes/recovery.ts +25 -42
  129. package/src/routes/route-support.ts +208 -1
  130. package/src/routes/snapshots.ts +4 -9
  131. package/src/routes/sync.ts +4 -7
  132. package/src/security/redaction.ts +29 -23
  133. package/src/sync/autosync-scheduler.test.ts +23 -0
  134. package/src/sync/autosync-scheduler.ts +6 -2
  135. package/src/sync/backup-scheduler.ts +3 -6
  136. package/src/sync/baseline-heal.ts +74 -0
  137. package/src/sync/push-precheck.ts +75 -0
  138. package/src/sync/sync-config.test.ts +24 -13
  139. package/src/sync/sync-engine.test.ts +88 -0
  140. package/src/sync/sync-engine.ts +33 -43
  141. package/src/ui/backup-inspect.ts +1 -1
  142. package/src/ui/dsh-profiles-view.ts +3 -5
  143. package/src/ui/history-model.test.ts +2 -1
  144. package/src/ui/history-model.ts +3 -2
  145. package/src/ui/i18n.test.ts +8 -3
  146. package/src/ui/overview-view.test.ts +12 -0
  147. package/src/ui/overview-view.ts +12 -4
  148. package/src/ui/snapshots-view.ts +2 -2
  149. package/src/utils/paths.test.ts +36 -1
  150. package/src/utils/paths.ts +30 -6
  151. package/src/utils/time.test.ts +46 -0
  152. package/src/utils/time.ts +55 -0
@@ -105,23 +105,31 @@ function replaceSensitiveField(text, re, blacklist) {
105
105
  });
106
106
  }
107
107
  /**
108
- * 文本脱敏(幂等)。blacklist 为**附加**规范化字段名(小写无分隔符,如 'clientsecret')。
109
- * 输出仍保留结构化形态(JSON 行合法)。
108
+ * 脱敏流水线(**唯一实现**,redact 与 createRedactor 共用一套顺序与语义)。
109
+ *
110
+ * 曾经这里与 createRedactor 各写一遍完全相同的 6 步(结构化 3 步 + 值形状 + URL query + userinfo),
111
+ * 两份代码只在「正则实例从哪来」上不同 —— 任何一步调整都要记得改两处,漏一次就是两条脱敏口径。
112
+ * 现在只由调用方决定正则实例的生命周期(模块级常量 / 每次预编译),流水线本身不再有副本。
110
113
  */
111
- export function redact(text, blacklist = []) {
112
- let out = text;
114
+ function redactPipeline(text, blacklist, json, kv, colon) {
113
115
  // 1. 结构化字段形态(顺序:JSON → kv → colon;JSON 键不会被后续形态二次命中)
114
- out = replaceSensitiveField(out, JSON_FIELD_RE, blacklist);
115
- out = replaceSensitiveField(out, KV_FIELD_RE, blacklist);
116
- out = replaceSensitiveField(out, COLON_FIELD_RE, blacklist);
116
+ let out = replaceSensitiveField(text, json, blacklist);
117
+ out = replaceSensitiveField(out, kv, blacklist);
118
+ out = replaceSensitiveField(out, colon, blacklist);
117
119
  // 2. 值形状模式(字段名无关,包含式)
118
120
  for (const { re } of VALUE_PATTERNS) {
119
121
  re.lastIndex = 0;
120
122
  out = out.replace(re, REDACTED);
121
123
  }
122
124
  out = out.replace(URL_QUERY_RE, `$1${REDACTED}`);
123
- out = out.replace(URL_USERINFO_RE, `$1${REDACTED}$3`);
124
- return out;
125
+ return out.replace(URL_USERINFO_RE, `$1${REDACTED}$3`);
126
+ }
127
+ /**
128
+ * 文本脱敏(幂等)。blacklist 为**附加**规范化字段名(小写无分隔符,如 'clientsecret')。
129
+ * 输出仍保留结构化形态(JSON 行合法)。
130
+ */
131
+ export function redact(text, blacklist = []) {
132
+ return redactPipeline(text, blacklist, JSON_FIELD_RE, KV_FIELD_RE, COLON_FIELD_RE);
125
133
  }
126
134
  /** 对象级掩码:字段名命中敏感名单 → 整值替换(返回新对象,不改原对象;结构与类型保留) */
127
135
  export function redactValue(value, blacklist = []) {
@@ -137,21 +145,16 @@ export function redactValue(value, blacklist = []) {
137
145
  }
138
146
  return out;
139
147
  }
140
- /** 预编译脱敏器(多次调用复用;blacklist 为附加规范化字段名) */
148
+ /**
149
+ * 预编译脱敏器(多次调用复用;blacklist 为附加规范化字段名)。
150
+ * 正则实例**在创建时**各复制一份:模块级常量若与本函数共享,多线程无害但会让「谁动了 lastIndex」
151
+ * 不可追溯;复制成本只有一次,换来每个脱敏器实例自持状态。
152
+ */
141
153
  export function createRedactor(blacklist = []) {
142
- const compiled = { json: JSON_FIELD_RE, kv: KV_FIELD_RE, colon: COLON_FIELD_RE };
143
- return (text) => {
144
- let out = replaceSensitiveField(text, new RegExp(compiled.json.source, 'g'), blacklist);
145
- out = replaceSensitiveField(out, new RegExp(compiled.kv.source, 'g'), blacklist);
146
- out = replaceSensitiveField(out, new RegExp(compiled.colon.source, 'g'), blacklist);
147
- for (const { re } of VALUE_PATTERNS) {
148
- re.lastIndex = 0;
149
- out = out.replace(re, REDACTED);
150
- }
151
- out = out.replace(URL_QUERY_RE, `$1${REDACTED}`);
152
- out = out.replace(URL_USERINFO_RE, `$1${REDACTED}$3`);
153
- return out;
154
- };
154
+ const json = new RegExp(JSON_FIELD_RE.source, 'g');
155
+ const kv = new RegExp(KV_FIELD_RE.source, 'g');
156
+ const colon = new RegExp(COLON_FIELD_RE.source, 'g');
157
+ return (text) => redactPipeline(text, blacklist, json, kv, colon);
155
158
  }
156
159
  /** 默认名单(文档用;redact 的默认附加名单为空,内置判定已含 DEFAULT_SECRET_FIELD_NAMES) */
157
160
  export { DEFAULT_SECRET_FIELD_NAMES };
@@ -743,11 +743,15 @@ export class AutoSyncScheduler {
743
743
  : partial
744
744
  ? conflictedSections
745
745
  : deferredSections;
746
+ // 0.4.1:推送前收养了「本机自己推上去的」远端快照(上次推送在写基线前被打断)→
747
+ // 如实记一条 skipReason,让历史与首页能说清「这次推上去之前先修好了基线」,
748
+ // 而不是让用户以为又发生了一次莫名冲突。冲突原因优先(真有冲突时更该被看见)。
749
+ const adoptedReason = pushReport.adoptedBase !== undefined ? 'baseline-adopted' : undefined;
746
750
  const result = {
747
751
  status: partial ? 'partial' : 'success',
748
752
  direction: appliedSections.length ? 'both' : 'push',
749
753
  appliedSections, pushedSnapshotId: pushReport.snapshotId, historyId,
750
- ...(skipReason !== undefined ? { skipReason } : {}),
754
+ ...(skipReason !== undefined || adoptedReason !== undefined ? { skipReason: skipReason ?? adoptedReason } : {}),
751
755
  ...(reportedConflicted.length > 0 ? { conflictedSections: reportedConflicted } : {}),
752
756
  consecutiveFailures: 0,
753
757
  ...forcedMark,
@@ -756,7 +760,7 @@ export class AutoSyncScheduler {
756
760
  direction: appliedSections.length ? 'both' : 'push',
757
761
  status: partial ? 'partial' : 'success',
758
762
  appliedSections, pushedSnapshotId: pushReport.snapshotId,
759
- ...(skipReason !== undefined ? { skipReason } : {}),
763
+ ...(skipReason !== undefined || adoptedReason !== undefined ? { skipReason: skipReason ?? adoptedReason } : {}),
760
764
  ...(reportedConflicted.length > 0 ? { conflictedSections: reportedConflicted } : {}),
761
765
  createdAt: nowIso, failureCountAtRun: 0,
762
766
  ...forcedMark,
@@ -7,6 +7,7 @@ import { readBackupSchedule, writeBackupSchedule, nextBackupDelayMs } from './ba
7
7
  import { shouldTriggerStartupRun } from './autosync-scheduler.js';
8
8
  import { AUTO_BACKUP_PREFIX, pruneAutoBackupsByPolicy } from './backup-files.js';
9
9
  import { DEFAULT_RETENTION_POLICY } from './retention-policy.js';
10
+ import { formatDateStamp } from '../utils/time.js';
10
11
  export class BackupScheduler {
11
12
  syncDir;
12
13
  exportsDir;
@@ -175,7 +176,7 @@ export class BackupScheduler {
175
176
  });
176
177
  // 显式落 exportsDir(与 host 路由同构;Exporter 缺省 outPath 是相对文件名,不落目录)
177
178
  // auto 前缀 = 定时备份产物标识:列表来源 Badge + cache-cleaner 豁免 + 保留策略清理依据
178
- const outPath = join(this.exportsDir, `${AUTO_BACKUP_PREFIX}${dateStamp(this.now())}-${randomBytes(3).toString('hex')}.zip`);
179
+ const outPath = join(this.exportsDir, `${AUTO_BACKUP_PREFIX}${formatDateStamp(this.now())}-${randomBytes(3).toString('hex')}.zip`);
179
180
  const { report } = await exporter.export({
180
181
  includeSecrets: false, // 恒不含 secret(与自动同步同语义)
181
182
  outPath,
@@ -304,9 +305,4 @@ export class BackupScheduler {
304
305
  }
305
306
  }
306
307
  }
307
- /** 导出文件时间戳(YYYYMMDD-HHmmss),与 host 路由 dateStamp 同构。 */
308
- function dateStamp(d) {
309
- const p = (n) => String(n).padStart(2, '0');
310
- return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
311
- }
312
308
  //# sourceMappingURL=backup-scheduler.js.map
@@ -0,0 +1,35 @@
1
+ import type { MsgFunc } from '../core/messages.ts';
2
+ import type { SnapshotFs } from './fs.ts';
3
+ import type { SyncSnapshotMeta } from './transport.ts';
4
+ export interface AdoptOwnRemoteHeadOptions {
5
+ /** sync-state.json 所在目录。 */
6
+ stateDir: string;
7
+ fsx: SnapshotFs;
8
+ /** 本地快照副本目录(祖先来源);缺省 = 本机没有副本可指。 */
9
+ localSnapshotsDir?: string;
10
+ /** 远端快照列表(已按 createdAt 升序)。 */
11
+ metas: readonly SyncSnapshotMeta[];
12
+ /** 判定为「比基线新」的那份远端快照 id。 */
13
+ remoteId: string;
14
+ /** 本机当前基线(仅用于告警文案)。 */
15
+ base: string;
16
+ /** 本次通道身份(写回 sync-state.transport)。 */
17
+ transport: {
18
+ type: string;
19
+ ref: string;
20
+ };
21
+ hostname: string;
22
+ msg: MsgFunc;
23
+ /** 出参:收养说明追加到这里(调用方原样带给用户)。 */
24
+ warnings: string[];
25
+ }
26
+ /**
27
+ * 把「本机自己推上去、但基线没跟上」的远端最新快照收养为基线。
28
+ *
29
+ * 只写 sync-state:lastSnapshotId / 每分区 hash(取**被收养快照自己**的 sectionHashes,
30
+ * 不是本次导出结果)/ 祖先目录名(本机真有该副本才指过去,没有就保持原祖先 —— 三方合并仍成立,
31
+ * 也不会被写成一个不存在的目录名)。
32
+ *
33
+ * @returns 被收养的快照 id;null = 不满足收养条件(调用方按冲突返回)
34
+ */
35
+ export declare function adoptOwnRemoteHead(opts: AdoptOwnRemoteHeadOptions): Promise<string | null>;
@@ -0,0 +1,39 @@
1
+ import { joinFs } from './fs.js';
2
+ import { loadSyncState, resolveDeviceIdentity, saveSyncState } from './sync-state.js';
3
+ /**
4
+ * 把「本机自己推上去、但基线没跟上」的远端最新快照收养为基线。
5
+ *
6
+ * 只写 sync-state:lastSnapshotId / 每分区 hash(取**被收养快照自己**的 sectionHashes,
7
+ * 不是本次导出结果)/ 祖先目录名(本机真有该副本才指过去,没有就保持原祖先 —— 三方合并仍成立,
8
+ * 也不会被写成一个不存在的目录名)。
9
+ *
10
+ * @returns 被收养的快照 id;null = 不满足收养条件(调用方按冲突返回)
11
+ */
12
+ export async function adoptOwnRemoteHead(opts) {
13
+ const meta = opts.metas.find((m) => m.id === opts.remoteId);
14
+ if (meta === undefined)
15
+ return null;
16
+ const device = await resolveDeviceIdentity(opts.stateDir, opts.hostname, opts.fsx, opts.msg);
17
+ const remoteDevice = meta.manifest.deviceId;
18
+ if (typeof remoteDevice !== 'string' || remoteDevice === '' || remoteDevice !== device.id)
19
+ return null;
20
+ const ancestorKnown = opts.localSnapshotsDir !== undefined
21
+ && await opts.fsx.isDir(joinFs(opts.localSnapshotsDir, opts.remoteId));
22
+ const state = await loadSyncState(opts.stateDir, opts.fsx, opts.msg);
23
+ state.lastSnapshotId = opts.remoteId;
24
+ if (ancestorKnown)
25
+ state.ancestorId = opts.remoteId;
26
+ for (const [sid, hash] of Object.entries(meta.sections)) {
27
+ if (typeof hash !== 'string' || hash === '')
28
+ continue;
29
+ state.sections[sid] = { hash, updatedAt: meta.createdAt };
30
+ }
31
+ state.transport = opts.transport;
32
+ await saveSyncState(opts.stateDir, state, opts.fsx);
33
+ opts.warnings.push(opts.msg(ancestorKnown ? 'sync.pushBaselineAdopted' : 'sync.pushBaselineAdoptedNoAncestor', {
34
+ remote: opts.remoteId,
35
+ base: opts.base,
36
+ }));
37
+ return opts.remoteId;
38
+ }
39
+ //# sourceMappingURL=baseline-heal.js.map
@@ -0,0 +1,35 @@
1
+ import type { SnapshotFs } from './fs.ts';
2
+ import type { RemoteSnapshotIndex } from './session-tombstones.ts';
3
+ import type { SyncTransport } from './transport.ts';
4
+ import type { MsgFunc } from '../core/messages.ts';
5
+ export interface PushBaseOptions {
6
+ stateDir: string;
7
+ fsx: SnapshotFs;
8
+ localSnapshotsDir?: string;
9
+ /** SYN-02:本轮已列过的远端 index(推进检测与墓碑继承共用同一份)。 */
10
+ index: RemoteSnapshotIndex;
11
+ transport: Pick<SyncTransport, 'type'> & {
12
+ ref: string;
13
+ };
14
+ hostname?: string;
15
+ msg: MsgFunc;
16
+ warnings: string[];
17
+ }
18
+ export type PushBaseOutcome = {
19
+ ok: true;
20
+ base: string;
21
+ adopted?: string;
22
+ } | {
23
+ ok: false;
24
+ message: string;
25
+ };
26
+ /**
27
+ * 判定本机能否继续推送,返回可用的基线。
28
+ *
29
+ * - 首次同步(没有基线)→ 放行;远端为空 → 放行(没有可比对的快照)。
30
+ * - 读不到远端列表 → **告警放行**(上传本身会再暴露通道问题),绝不把「读不到」当「没变」。
31
+ * - 远端最新快照就是当前基线 → 放行。
32
+ * - 远端最新快照是本机自己推的 → 收养为基线后放行(`adopted` 回传,调用方写进报告)。
33
+ * - 其余(别的设备的改动 / 没有 deviceId 的旧快照)→ 冲突拒绝,给 force 出口。
34
+ */
35
+ export declare function resolvePushBase(opts: PushBaseOptions): Promise<PushBaseOutcome>;
@@ -0,0 +1,58 @@
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.js';
15
+ import { loadSyncState } from './sync-state.js';
16
+ /**
17
+ * 判定本机能否继续推送,返回可用的基线。
18
+ *
19
+ * - 首次同步(没有基线)→ 放行;远端为空 → 放行(没有可比对的快照)。
20
+ * - 读不到远端列表 → **告警放行**(上传本身会再暴露通道问题),绝不把「读不到」当「没变」。
21
+ * - 远端最新快照就是当前基线 → 放行。
22
+ * - 远端最新快照是本机自己推的 → 收养为基线后放行(`adopted` 回传,调用方写进报告)。
23
+ * - 其余(别的设备的改动 / 没有 deviceId 的旧快照)→ 冲突拒绝,给 force 出口。
24
+ */
25
+ export async function resolvePushBase(opts) {
26
+ const state = await loadSyncState(opts.stateDir, opts.fsx, opts.msg);
27
+ const base = state.lastSnapshotId;
28
+ if (base === '')
29
+ return { ok: true, base };
30
+ if (opts.index.reason !== undefined) {
31
+ opts.warnings.push(opts.msg('sync.pushAdvanceCheckFailed', { reason: opts.index.reason }));
32
+ return { ok: true, base };
33
+ }
34
+ const metas = opts.index.metas;
35
+ if (metas.length === 0)
36
+ return { ok: true, base };
37
+ const latest = metas[metas.length - 1].id; // list 按 createdAt 升序 → 最新在末
38
+ if (latest === base)
39
+ return { ok: true, base };
40
+ const adopted = await adoptOwnRemoteHead({
41
+ stateDir: opts.stateDir,
42
+ fsx: opts.fsx,
43
+ localSnapshotsDir: opts.localSnapshotsDir,
44
+ metas,
45
+ remoteId: latest,
46
+ base,
47
+ transport: opts.transport,
48
+ hostname: opts.hostname ?? os.hostname(),
49
+ msg: opts.msg,
50
+ warnings: opts.warnings,
51
+ });
52
+ if (adopted === null) {
53
+ // 无法安全断言「远端没变」时的保守拒绝:不 upload、不记基线、不改 sync-state。
54
+ return { ok: false, message: opts.msg('sync.pushRemoteAdvanced', { remote: latest, base }) };
55
+ }
56
+ return { ok: true, base: adopted, adopted };
57
+ }
58
+ //# sourceMappingURL=push-precheck.js.map
@@ -138,6 +138,15 @@ export interface SyncPushReport {
138
138
  * 而不是记成「同步失败」。
139
139
  */
140
140
  conflict?: boolean;
141
+ /**
142
+ * 本次推送前**收养了本机自己推上去的远端最新快照**(0.4.1 自愈):该值 = 被收养的快照 id。
143
+ *
144
+ * 触发场景:上次推送在上传成功、写基线之前被打断(进程退出/崩溃/断电),远端已前进而本机
145
+ * `lastSnapshotId` 仍是上一版 → 前置检测会永久拒绝推送(每次都说「远端被别人推进了」),
146
+ * 单设备用户因此被自己的快照锁死。判据只看「远端最新快照的 manifest.deviceId == 本机
147
+ * deviceId」,别的设备推进过就仍然按冲突返回,绝不越过。
148
+ */
149
+ adoptedBase?: string;
141
150
  }
142
151
  /** 差异报告中的单个变更项(PlanItem 摘要,不含敏感细节) */
143
152
  export interface PullChange {
@@ -516,18 +525,6 @@ export declare class SyncEngine {
516
525
  private pruneRemoteSnapshots;
517
526
  /** 读取远端保留策略;提供者缺失/抛错 → 缺省策略(保守多留,绝不因读取失败误删)。 */
518
527
  private resolveRetentionPolicy;
519
- /**
520
- * push 前置:远端是否已被别的设备推进(防「推上去把别人的改动架空」)。
521
- *
522
- * 判据与 hasNewRemoteSnapshot() 同源但方向相反:
523
- * - 首次同步(lastSnapshotId === '')→ **不拦**(本机没有基线可丢,第一次推送就是建立基线);
524
- * - 远端为空 → 不拦(没有可比对的快照);
525
- * - 其余:远端最新快照 id !== lastSnapshotId ⇒ 远端被推进(或本机基线已被裁剪)→ 拦。
526
- * 两种情况都**无法安全断言「远端没变」**,保守拒绝并给出 force 出口。
527
- * - list() 抛错 → 返回 reason(调用方按原样继续并告警),绝不把「读不到」当成「没变」。
528
- * - SYN-02:index 可由 push() 传入(同一轮只列一次远端),缺省自己 list(其它调用点行为不变)。
529
- */
530
- private remoteAdvancedCheck;
531
528
  /**
532
529
  * pull:拉取远端最新(或指定)快照 → 过滤 portable 分区 → 转临时标准 ZIP →
533
530
  * 复用 Importer 预览流程(analyzeImport/createImportPlan)产出差异报告。
@@ -33,6 +33,7 @@ import { stringifyJsonSafe } from '../utils/json.js';
33
33
  import { writeZip } from '../utils/zip.js';
34
34
  import { createSnapshotFs, joinFs } from './fs.js';
35
35
  import { writeSnapshotToDir } from './layout.js';
36
+ import { resolvePushBase } from './push-precheck.js';
36
37
  import { credentialsMapFromYaml, decryptCredentialsPayload, decryptSectionsPayload, encryptCredentialsPayload, encryptSectionsPayload, } from './snapshot-crypto.js';
37
38
  import { OPT_IN_SYNC_SECTIONS } from './sync-selection.js';
38
39
  import { listRemoteSnapshotIndex, planSessionBookkeeping, remoteTombstonesOf, stripTombstonedSessionsInPlace, } from './session-tombstones.js';
@@ -64,6 +65,8 @@ const zh = {
64
65
  'sync.applyMergeResolutionsNoImporter': 'applyMergeResolutions: SyncEngine 缺少 importer(需在 options 中注入)',
65
66
  'sync.mergePendingConflicts': '仍有 {count} 个分区未裁决({sections}):已裁决的部分已写入本机,但基线不推进,冲突下一轮会重新出现',
66
67
  'sync.baselineRexportFailed': '写回成功但重新导出本机分区失败({sections}):无法证明基线与本机一致,本次**不记基线**(远端指针保持原值,下一轮重新合并收敛)',
68
+ 'sync.pushBaselineAdopted': '远端最新快照 {remote} 是本机上次推送的(本机基线停在 {base},上次推送在记录基线前被打断):已把它收养为基线并继续本次推送',
69
+ 'sync.pushBaselineAdoptedNoAncestor': '远端最新快照 {remote} 是本机上次推送的,但本机没有它的本地祖先副本:已收养基线(下次合并退化为两方合并,结果仍安全)',
67
70
  };
68
71
  const en = {
69
72
  'sync.pushRemoteAdvanced': 'The newest remote snapshot {remote} differs from the local baseline {base}: this push did not run (nothing written remotely, baseline untouched). Sync the remote changes first, or explicitly force the push if this machine should overwrite the remote.',
@@ -72,6 +75,8 @@ const en = {
72
75
  'sync.applyMergeResolutionsNoImporter': 'applyMergeResolutions: SyncEngine is missing the importer (must be injected via options)',
73
76
  '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',
74
77
  '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)',
78
+ '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',
79
+ '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)',
75
80
  };
76
81
  registerMessageCatalog({ id: 'sync-engine-merge', zh, en });
77
82
  /** plan 的单个分区结果 → 预览视图(三侧都只回传可读文本,绝不回传原始值)。 */
@@ -478,6 +483,8 @@ export class SyncEngine {
478
483
  */
479
484
  async push(opts = {}) {
480
485
  const warnings = [];
486
+ /** 0.4.1:本次推送前收养的「本机自己推的」远端快照(非空 ⇒ 上次推送被打断过,已在报告里如实回传) */
487
+ let adopted;
481
488
  const includeSecrets = opts.includeSecrets ?? false;
482
489
  const encrypt = opts.encrypt ?? false;
483
490
  // 安全不变量:导出密钥必须加密;加密必须给密码(密码绝不落盘)
@@ -490,24 +497,17 @@ export class SyncEngine {
490
497
  // SYN-02:本轮只列一次远端 index(推进检测 + 继承会话删除墓碑共用;墓碑累积在最新快照里)
491
498
  const remoteIndex = await listRemoteSnapshotIndex(this.transport);
492
499
  const remoteTombstones = remoteIndex.reason === undefined ? remoteTombstonesOf(remoteIndex.metas) : [];
493
- // 远端推进检测:不一致 = 远端被别的设备推过(或本机基线已被裁剪)。
494
- // 此时推上去会覆盖/架空别人的改动 → 直接返回冲突(**不抛错**、不 upload、不记基线、不改 sync-state)。
500
+ // 远端推进检测(判据与 0.4.1 自愈收养全在 push-precheck.ts);冲突时**不抛错**、
501
+ // 不 upload、不记基线、不改 sync-state,只把文案回给调用方走 force 出口。
495
502
  if (opts.force !== true) {
496
- const check = await this.remoteAdvancedCheck(remoteIndex);
497
- if (check.reason !== undefined) {
498
- // 读不到远端列表 ⇒ 无法判定。按原样继续(上传本身会再暴露通道问题),但如实说明。
499
- warnings.push(this.msg('sync.pushAdvanceCheckFailed', { reason: check.reason }));
500
- }
501
- else if (check.blocked) {
502
- return {
503
- ok: false,
504
- snapshotId: '',
505
- sections: [],
506
- warnings,
507
- conflict: true,
508
- message: this.msg('sync.pushRemoteAdvanced', { remote: check.latest, base: check.base }),
509
- };
510
- }
503
+ const pre = await resolvePushBase({
504
+ stateDir: this.stateDir, fsx: this.fsx, localSnapshotsDir: this.localSnapshotsDir,
505
+ index: remoteIndex, transport: { type: this.transport.type, ref: this.transportRef },
506
+ msg: this.msg, warnings,
507
+ });
508
+ if (!pre.ok)
509
+ return { ok: false, snapshotId: '', sections: [], warnings, conflict: true, message: pre.message };
510
+ adopted = pre.adopted;
511
511
  }
512
512
  const plainSections = {};
513
513
  const targets = this.pushTargets(opts.sections, warnings);
@@ -607,7 +607,13 @@ export class SyncEngine {
607
607
  ? { sessionUnits: bookkeeping.sessionUnits, deletedSessions: bookkeeping.tombstones }
608
608
  : {}),
609
609
  });
610
- return { ok: true, snapshotId: id, sections: Object.keys(plainSections), warnings };
610
+ return {
611
+ ok: true,
612
+ snapshotId: id,
613
+ sections: Object.keys(plainSections),
614
+ warnings,
615
+ ...(adopted !== undefined ? { adoptedBase: adopted } : {}),
616
+ };
611
617
  }
612
618
  /**
613
619
  * P0-②:push 前只读预览「将推送什么」—— 零写入、零远端变更:
@@ -806,31 +812,6 @@ export class SyncEngine {
806
812
  return DEFAULT_RETENTION_POLICY;
807
813
  }
808
814
  }
809
- /**
810
- * push 前置:远端是否已被别的设备推进(防「推上去把别人的改动架空」)。
811
- *
812
- * 判据与 hasNewRemoteSnapshot() 同源但方向相反:
813
- * - 首次同步(lastSnapshotId === '')→ **不拦**(本机没有基线可丢,第一次推送就是建立基线);
814
- * - 远端为空 → 不拦(没有可比对的快照);
815
- * - 其余:远端最新快照 id !== lastSnapshotId ⇒ 远端被推进(或本机基线已被裁剪)→ 拦。
816
- * 两种情况都**无法安全断言「远端没变」**,保守拒绝并给出 force 出口。
817
- * - list() 抛错 → 返回 reason(调用方按原样继续并告警),绝不把「读不到」当成「没变」。
818
- * - SYN-02:index 可由 push() 传入(同一轮只列一次远端),缺省自己 list(其它调用点行为不变)。
819
- */
820
- async remoteAdvancedCheck(index) {
821
- const state = await loadSyncState(this.stateDir, this.fsx, this.msg);
822
- const base = state.lastSnapshotId;
823
- if (base === '')
824
- return { blocked: false, base, latest: '' };
825
- const listed = index ?? await listRemoteSnapshotIndex(this.transport);
826
- if (listed.reason !== undefined)
827
- return { blocked: false, base, latest: '', reason: listed.reason };
828
- const metas = listed.metas;
829
- if (metas.length === 0)
830
- return { blocked: false, base, latest: '' };
831
- const latest = metas[metas.length - 1].id; // list 按 createdAt 升序 → 最新在末
832
- return { blocked: latest !== base, base, latest };
833
- }
834
815
  /**
835
816
  * pull:拉取远端最新(或指定)快照 → 过滤 portable 分区 → 转临时标准 ZIP →
836
817
  * 复用 Importer 预览流程(analyzeImport/createImportPlan)产出差异报告。
@@ -34,7 +34,7 @@ export declare function inspectSections(analysis: ImportAnalysis, plan: ImportPl
34
34
  export declare function inspectSummary(analysis: ImportAnalysis, plan: ImportPlan): BackupInspectSummary;
35
35
  /** 变更明细分组键(渲染顺序 = 冲突 → 变更 → 路径映射 → 一致跳过 → 其他)。 */
36
36
  export type InspectGroupKey = 'conflicts' | 'changes' | 'paths' | 'skipped' | 'others';
37
- /** 单分组:key(语义)+ kind(Badge/kindTag 颜色语义)+ 组内条目。 */
37
+ /** 单分组:key(语义)+ kind(Badge 四态颜色语义)+ 组内条目。 */
38
38
  export interface InspectChangeGroup {
39
39
  key: InspectGroupKey;
40
40
  /** 颜色语义:error=冲突 / info=变更 / warn=路径映射与其它 / ok=一致跳过 */
@@ -1,13 +1,3 @@
1
- /**
2
- * 「档案」页(DSH profile 管理)—— 框架无关纯函数层(node 可测)。
3
- *
4
- * 职责:名字输入校验、列表排序(当前运行置顶)、列表摘要统计、危险态判定、运行中实例判定、
5
- * 展示格式化(时间/字节)、终端启动命令文本。不产出用户可见散文(文案走 locale 字典 `t()`),
6
- * 不 import node 模块、不 import React。
7
- *
8
- * 依赖方向:只从 `src/profiles/dsh-profile-shared.ts`(零依赖)取类型与纯函数——
9
- * 绝不 import 用 node fs 的引擎(否则 client bundle 会带上 node 内置模块依赖而整插件不加载)。
10
- */
11
1
  import { type DshProfileCopyWarning, type DshProfileIssue, type DshProfileLaunchResult, type DshProfileLaunchWarning, type DshProfileMeta, type DshProfileRunningView, type DshProfileShape, type DshProfileStopOutcome } from '../profiles/dsh-profile-shared.ts';
12
2
  /** 名称输入校验结果(UI 按码映射 i18n;null = 合法)。 */
13
3
  export type ProfileNameIssue = 'required' | 'tooLong' | 'illegal' | 'reserved';
@@ -8,6 +8,7 @@
8
8
  * 依赖方向:只从 `src/profiles/dsh-profile-shared.ts`(零依赖)取类型与纯函数——
9
9
  * 绝不 import 用 node fs 的引擎(否则 client bundle 会带上 node 内置模块依赖而整插件不加载)。
10
10
  */
11
+ import { formatMinuteStamp, parseDateInput } from '../utils/time.js';
11
12
  import { checkProfileName, isLaunchableShape, isManagedProfileName, } from '../profiles/dsh-profile-shared.js';
12
13
  /** 校验输入框里的 profile 名:与 host 侧同规则,但把「空」与「过长」细分以便给出更准的提示。 */
13
14
  export function validateProfileNameInput(name) {
@@ -237,13 +238,8 @@ export function issueLabelKey(issue) {
237
238
  }
238
239
  /** 时间戳(毫秒)→ 本地 `YYYY-MM-DD HH:mm`;null / 非法 = 空串。 */
239
240
  export function formatProfileTime(ms) {
240
- if (ms === null)
241
- return '';
242
- const d = new Date(ms);
243
- if (Number.isNaN(d.getTime()))
244
- return '';
245
- const p = (n) => String(n).padStart(2, '0');
246
- return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
241
+ const d = parseDateInput(ms);
242
+ return d === null ? '' : formatMinuteStamp(d);
247
243
  }
248
244
  /** 字节数 → 人类可读(B / KB / MB,保留一位小数)。 */
249
245
  export function formatBytes(bytes) {
@@ -4,7 +4,8 @@ export function resultBadgeKind(result) {
4
4
  return 'ok';
5
5
  if (result === 'failed')
6
6
  return 'error';
7
- return 'warn'; // skipped
7
+ // pending(0.4.1)= 跑完了但还有待裁决项:绝不当成失败(红),也不是跳过 —— 用琥珀告警色
8
+ return 'warn'; // skipped / pending
8
9
  }
9
10
  export function kindLabelKey(kind) {
10
11
  return `history.kind.${kind}`;
@@ -17,7 +18,7 @@ export const HISTORY_KIND_OPTIONS = [
17
18
  'backup', 'backup-manual', 'snapshot-delete', 'snapshot-prune',
18
19
  ];
19
20
  /** 结果过滤选项。 */
20
- export const HISTORY_RESULT_OPTIONS = ['success', 'failed', 'skipped'];
21
+ export const HISTORY_RESULT_OPTIONS = ['success', 'pending', 'skipped', 'failed'];
21
22
  /** 把 UI 过滤模型转为后端 query 参数(kind/recent 转 kinds/recent 语义)。 */
22
23
  export function filterToQuery(f) {
23
24
  const q = {};
@@ -40,7 +40,7 @@ export interface OverviewSyncLite {
40
40
  export interface OverviewHistoryLite {
41
41
  at: string;
42
42
  kind: string;
43
- result: 'success' | 'failed' | 'skipped';
43
+ result: 'success' | 'failed' | 'skipped' | 'pending';
44
44
  summary: string;
45
45
  }
46
46
  /** Overview 数据输入(null = 未加载/加载失败;组件逐项就绪逐项传入)。 */
@@ -124,8 +124,8 @@ export declare function overviewHealth(inputs: OverviewInputs): OverviewHealth;
124
124
  export declare function overviewKindKey(kind: string): string;
125
125
  export interface OverviewActivityItem {
126
126
  at: string;
127
- /** 徽章语义(success→ok / failed→error / skipped→warn,与 history-model 同判定)。 */
128
- badge: 'ok' | 'error' | 'warn';
127
+ /** 徽章语义(success→ok / failed→error / skipped→warn / pending→pending,与 history-model 同判定)。 */
128
+ badge: 'ok' | 'error' | 'warn' | 'pending';
129
129
  /** UI 渲染 key(`overview.kind.<kind>`;未知 kind 归一为 other → `overview.kind.other`)。 */
130
130
  kindKey: string;
131
131
  /** 原始摘要(上层渲染前 redact())。 */
@@ -199,7 +199,15 @@ export function overviewActivity(history, limit = 5) {
199
199
  });
200
200
  return sorted.slice(0, limit).map((e) => ({
201
201
  at: e.at,
202
- badge: e.result === 'success' ? 'ok' : e.result === 'failed' ? 'error' : 'warn',
202
+ badge: e.result === 'success'
203
+ ? 'ok'
204
+ : e.result === 'failed'
205
+ ? 'error'
206
+ // pending:跑完了但仍有待裁决项(自动同步下行冲突未裁决)—— 首页必须说「待裁决」,
207
+ // 既不能红成「失败」,也不该混进「跳过」(那一轮确有上传/应用发生)
208
+ : e.result === 'pending'
209
+ ? 'pending'
210
+ : 'warn',
203
211
  kindKey: overviewKindKey(e.kind),
204
212
  summary: e.summary,
205
213
  }));
@@ -1,17 +1,3 @@
1
- /**
2
- * 备份页(Backups:快照恢复 / 备份文件 / 定时备份设置)—— 框架无关纯函数层(node 可测)。
3
- *
4
- * t43 从 `src/client/snapshots/SnapshotsPanel.tsx` 下沉(该组件原先把这些逻辑私有在函数体内,
5
- * 违反仓库铁律「逻辑放 src/ui」——node 无法测试)。本层职责:
6
- * - 面板状态切片 ← runStore 快照切片 的投影(切页/刷新恢复的判定);
7
- * - 状态/档位 → **字典键**(本层不产出任何用户可见文案,由 React 壳 t() 渲染,见 backup-schedule.ts 同款约定);
8
- * - 时间与文件名的展示格式化;
9
- * - 备份文件列表的搜索过滤、备注可读性判定;
10
- * - 恢复计划是否含可执行动作(执行按钮的 disabled 判据)。
11
- *
12
- * 约束:不 import node 模块、不 import `../client/*`(架构边界 tests/architecture-boundaries.test.ts)、
13
- * 无 React 依赖;类型仅从 `../core/*` / `../sync/*` 以 type-only 方式取(运行时不加载)。
14
- */
15
1
  import type { RestorePlan, RestoreReport, SnapshotMeta } from '../core/restore.ts';
16
2
  import type { RestoreChangeSummary } from '../core/snapshot-diff.ts';
17
3
  import type { BackupFileMeta } from '../sync/backup-files.ts';
@@ -1,3 +1,18 @@
1
+ /**
2
+ * 备份页(Backups:快照恢复 / 备份文件 / 定时备份设置)—— 框架无关纯函数层(node 可测)。
3
+ *
4
+ * t43 从 `src/client/snapshots/SnapshotsPanel.tsx` 下沉(该组件原先把这些逻辑私有在函数体内,
5
+ * 违反仓库铁律「逻辑放 src/ui」——node 无法测试)。本层职责:
6
+ * - 面板状态切片 ← runStore 快照切片 的投影(切页/刷新恢复的判定);
7
+ * - 状态/档位 → **字典键**(本层不产出任何用户可见文案,由 React 壳 t() 渲染,见 backup-schedule.ts 同款约定);
8
+ * - 时间与文件名的展示格式化;
9
+ * - 备份文件列表的搜索过滤、备注可读性判定;
10
+ * - 恢复计划是否含可执行动作(执行按钮的 disabled 判据)。
11
+ *
12
+ * 约束:不 import node 模块、不 import `../client/*`(架构边界 tests/architecture-boundaries.test.ts)、
13
+ * 无 React 依赖;类型仅从 `../core/*` / `../sync/*` 以 type-only 方式取(运行时不加载)。
14
+ */
15
+ import { formatMinuteStamp } from '../utils/time.js';
1
16
  export const INITIAL_SNAPSHOTS_PANEL_STATE = {
2
17
  status: 'loading',
3
18
  error: null,
@@ -120,8 +135,7 @@ export function formatBackupFileTime(ms) {
120
135
  const d = new Date(ms);
121
136
  if (Number.isNaN(d.getTime()))
122
137
  return '';
123
- const p = (n) => String(n).padStart(2, '0');
124
- return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
138
+ return formatMinuteStamp(d);
125
139
  }
126
140
  /**
127
141
  * 备注是否「编码损坏」(全问号/控制符)→ 调用方改渲染 backupFiles.noteUnreadable 文案;