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
@@ -449,30 +449,41 @@ test('t32 源码守卫:地面代码里通道数组只有一处声明(其余
449
449
  * 同一实验里 t32 的旧守卫(原文 includes)会误报 —— 正是本守卫存在的原因;
450
450
  * - 把诱饵换成真实代码 → 本守卫变红并报出行号(当时为 5868 / 5869)。
451
451
  */
452
- test('t33/B7 源码守卫:src/index.ts 不再手写通道数组/裸通道三元,全部消费单一来源', async () => {
453
- const indexSrc = await fs.readFile(fileURLToPath(new URL('../index.ts', import.meta.url)), 'utf8')
454
- const tplMode = stripJsComments(indexSrc, true, false)
455
- const opaqueMode = stripJsComments(indexSrc, false, true)
452
+ test('t33/B7 源码守卫:宿主侧两处源码不再手写通道数组/裸通道三元,全部消费单一来源', async () => {
453
+ // parseSyncBody 家族已下沉到 src/routes/route-support.ts(tech-debt #23)——宿主侧消费点因此分两处:
454
+ // 组合根源码与共享路由工具都必须在单一来源上取值,故一起扫、一起断言。
455
+ const sources: Array<[string, string]> = [
456
+ ['src/index.ts', await fs.readFile(fileURLToPath(new URL('../index.ts', import.meta.url)), 'utf8')],
457
+ ['src/routes/route-support.ts', await fs.readFile(fileURLToPath(new URL('../routes/route-support.ts', import.meta.url)), 'utf8')],
458
+ ]
459
+ const tplModes: string[] = []
460
+ const bad: string[] = []
461
+ for (const [sourceLabel, sourceText] of sources) {
462
+ const tplMode = stripJsComments(sourceText, true, false)
463
+ const opaqueMode = stripJsComments(sourceText, false, true)
464
+ tplModes.push(tplMode)
456
465
  const tplLines = tplMode.split(String.fromCharCode(10))
457
466
  const opaqueLines = opaqueMode.split(String.fromCharCode(10))
458
- const bad: string[] = []
459
467
  tplLines.forEach((line, i) => {
460
468
  const t = line.trim()
461
469
  // 只有两趟都认为这里是「真实代码」时才判定(注释在其中一趟必被清空)
462
470
  if (t === '' || (opaqueLines[i] ?? '').trim() === '') return
463
- if (t.includes("['git', 'webdav']") || t.includes("['git','webdav']")) bad.push(String(i + 1) + ': 通道数组字面量 ' + t)
464
- if (t.includes("? 'webdav' : 'git'") || t.includes("?'webdav':'git'")) bad.push(String(i + 1) + ': 裸通道三元判定 ' + t)
471
+ if (t.includes("['git', 'webdav']") || t.includes("['git','webdav']")) bad.push(sourceLabel + ':' + String(i + 1) + ': 通道数组字面量 ' + t)
472
+ if (t.includes("? 'webdav' : 'git'") || t.includes("?'webdav':'git'")) bad.push(sourceLabel + ':' + String(i + 1) + ': 裸通道三元判定 ' + t)
465
473
  })
466
- assert.deepEqual(bad, [], 'src/index.ts 不得再手写通道判定/枚举(应消费 channelOf / parseSyncChannel / SYNC_CHANNELS):' + String.fromCharCode(10) + bad.join(String.fromCharCode(10)))
474
+ }
475
+ const allTpl = tplModes.join(String.fromCharCode(10))
476
+ assert.deepEqual(bad, [], '宿主侧两处源码都不得再手写通道判定/枚举(应消费 channelOf / parseSyncChannel / SYNC_CHANNELS):' + String.fromCharCode(10) + bad.join(String.fromCharCode(10)))
467
477
  // 正向断言:确实接上了单一来源(否则上面可能因「什么都没写」而假绿)
468
478
  assert.ok(
469
- tplMode.includes('channelOf, parseSyncChannel, SYNC_CHANNELS')
470
- || (tplMode.includes('parseSyncChannel') && tplMode.includes('channelOf')),
471
- 'src/index.ts 必须从 ./sync/sync-config.ts 导入单一来源 API',
479
+ allTpl.includes('channelOf')
480
+ && allTpl.includes('parseSyncChannel')
481
+ && allTpl.includes('SYNC_CHANNELS'),
482
+ '宿主侧必须从 ./sync/sync-config.ts 导入单一来源 API(channelOf / parseSyncChannel / SYNC_CHANNELS)',
472
483
  )
473
484
  assert.ok(
474
- tplMode.includes('for (const channel of SYNC_CHANNELS)') || tplMode.includes('SYNC_CHANNELS.map('),
475
- 'src/index.ts 的通道集合必须由 SYNC_CHANNELS 派生(不得穷举字面量)',
485
+ allTpl.includes('for (const channel of SYNC_CHANNELS)') || allTpl.includes('SYNC_CHANNELS.map('),
486
+ '宿主侧的通道集合必须由 SYNC_CHANNELS 派生(不得穷举字面量)',
476
487
  )
477
488
  })
478
489
 
@@ -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,7 @@ export function inspectSummary(analysis: ImportAnalysis, plan: ImportPlan): Back
56
56
  /** 变更明细分组键(渲染顺序 = 冲突 → 变更 → 路径映射 → 一致跳过 → 其他)。 */
57
57
  export type InspectGroupKey = 'conflicts' | 'changes' | 'paths' | 'skipped' | 'others';
58
58
 
59
- /** 单分组:key(语义)+ kind(Badge/kindTag 颜色语义)+ 组内条目。 */
59
+ /** 单分组:key(语义)+ kind(Badge 四态颜色语义)+ 组内条目。 */
60
60
  export interface InspectChangeGroup {
61
61
  key: InspectGroupKey;
62
62
  /** 颜色语义:error=冲突 / info=变更 / warn=路径映射与其它 / ok=一致跳过 */
@@ -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.ts'
11
12
  import {
12
13
  checkProfileName, isLaunchableShape, isManagedProfileName,
13
14
  type DshProfileCopyWarning, type DshProfileIssue, type DshProfileLaunchResult, type DshProfileLaunchWarning,
@@ -361,11 +362,8 @@ export function issueLabelKey(issue: DshProfileIssue): 'profiles.issue.manifestI
361
362
 
362
363
  /** 时间戳(毫秒)→ 本地 `YYYY-MM-DD HH:mm`;null / 非法 = 空串。 */
363
364
  export function formatProfileTime(ms: number | null): string {
364
- if (ms === null) return ''
365
- const d = new Date(ms)
366
- if (Number.isNaN(d.getTime())) return ''
367
- const p = (n: number): string => String(n).padStart(2, '0')
368
- return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
365
+ const d = parseDateInput(ms)
366
+ return d === null ? '' : formatMinuteStamp(d)
369
367
  }
370
368
 
371
369
  /** 字节数 → 人类可读(B / KB / MB,保留一位小数)。 */
@@ -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 {
@@ -19,7 +19,7 @@
19
19
  */
20
20
  import test from 'node:test';
21
21
  import assert from 'node:assert/strict';
22
- import { readFileSync } from 'node:fs';
22
+ import { readFileSync, readdirSync } from 'node:fs';
23
23
 
24
24
  import { makeUiT, uiEn, uiZh, zhUiT } from './i18n.ts';
25
25
  import {
@@ -183,8 +183,13 @@ test('i18n-08 英文字典不留 (s)/(ies) 括号式复数(今日起由 plural
183
183
  }
184
184
  };
185
185
  collect(uiEn, 'uiEn');
186
- // 客户端四本字典同查:改的是源码文本,不 import(client 侧不保证可被 node 直接加载)
187
- for (const rel of ['../client/locales.ts', '../client/sync/sync-locales.ts', '../client/market/market-locales.ts', '../client/recovery/recovery-locales.ts']) {
186
+ // 客户端字典同查:改的是源码文本,不 import(client 侧不保证可被 node 直接加载)
187
+ // tech-debt #22:主字典按域拆成 src/client/locales/*.ts(聚合器只剩展开语句)⇒ 逐个分域文件扫,覆盖率不降
188
+ const splitDicts = readdirSync(new URL('../client/locales/', import.meta.url))
189
+ .filter((name) => name.endsWith('.ts'))
190
+ .sort()
191
+ .map((name) => '../client/locales/' + name);
192
+ for (const rel of [...splitDicts, '../client/sync/sync-locales.ts', '../client/market/market-locales.ts', '../client/recovery/recovery-locales.ts']) {
188
193
  const text = readFileSync(new URL(rel, import.meta.url), 'utf8');
189
194
  for (const line of text.split('\n')) {
190
195
  if (/\((s|ies)\)/.test(line) && !/http\(s\)/.test(line) && /:\s*'/.test(line)) offenders.push(rel + ' :: ' + line.trim());
@@ -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', () => {
@@ -45,7 +45,7 @@ export interface OverviewSyncLite {
45
45
  export interface OverviewHistoryLite {
46
46
  at: string
47
47
  kind: string
48
- result: 'success' | 'failed' | 'skipped'
48
+ result: 'success' | 'failed' | 'skipped' | 'pending'
49
49
  summary: string
50
50
  }
51
51
 
@@ -290,8 +290,8 @@ export function overviewKindKey(kind: string): string {
290
290
 
291
291
  export interface OverviewActivityItem {
292
292
  at: string
293
- /** 徽章语义(success→ok / failed→error / skipped→warn,与 history-model 同判定)。 */
294
- badge: 'ok' | 'error' | 'warn'
293
+ /** 徽章语义(success→ok / failed→error / skipped→warn / pending→pending,与 history-model 同判定)。 */
294
+ badge: 'ok' | 'error' | 'warn' | 'pending'
295
295
  /** UI 渲染 key(`overview.kind.<kind>`;未知 kind 归一为 other → `overview.kind.other`)。 */
296
296
  kindKey: string
297
297
  /** 原始摘要(上层渲染前 redact())。 */
@@ -311,7 +311,15 @@ export function overviewActivity(
311
311
  })
312
312
  return sorted.slice(0, limit).map((e) => ({
313
313
  at: e.at,
314
- badge: e.result === 'success' ? 'ok' : e.result === 'failed' ? 'error' : 'warn',
314
+ badge: e.result === 'success'
315
+ ? 'ok'
316
+ : e.result === 'failed'
317
+ ? 'error'
318
+ // pending:跑完了但仍有待裁决项(自动同步下行冲突未裁决)—— 首页必须说「待裁决」,
319
+ // 既不能红成「失败」,也不该混进「跳过」(那一轮确有上传/应用发生)
320
+ : e.result === 'pending'
321
+ ? 'pending'
322
+ : 'warn',
315
323
  kindKey: overviewKindKey(e.kind),
316
324
  summary: e.summary,
317
325
  }))
@@ -12,6 +12,7 @@
12
12
  * 约束:不 import node 模块、不 import `../client/*`(架构边界 tests/architecture-boundaries.test.ts)、
13
13
  * 无 React 依赖;类型仅从 `../core/*` / `../sync/*` 以 type-only 方式取(运行时不加载)。
14
14
  */
15
+ import { formatMinuteStamp } from '../utils/time.ts'
15
16
  import type { RestorePlan, RestoreReport, SnapshotMeta } from '../core/restore.ts'
16
17
  import type { RestoreChangeSummary } from '../core/snapshot-diff.ts'
17
18
  import type { BackupFileMeta } from '../sync/backup-files.ts'
@@ -210,8 +211,7 @@ export function filterBackupFiles(files: readonly BackupFileMeta[], query: strin
210
211
  export function formatBackupFileTime(ms: number): string {
211
212
  const d = new Date(ms)
212
213
  if (Number.isNaN(d.getTime())) return ''
213
- const p = (n: number): string => String(n).padStart(2, '0')
214
- return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
214
+ return formatMinuteStamp(d)
215
215
  }
216
216
 
217
217
  /**
@@ -7,7 +7,8 @@
7
7
  */
8
8
  import test from 'node:test';
9
9
  import assert from 'node:assert/strict';
10
- import { applyPrefixMappings } from './paths.ts';
10
+ import path from 'node:path';
11
+ import { applyPrefixMappings, isPathInside, isSameOrChild } from './paths.ts';
11
12
  import type { PathMapping } from '../core/types.ts';
12
13
 
13
14
  /** 测试用映射(appliesTo 与语义无关,任选一个合法分区) */
@@ -61,3 +62,37 @@ test('core-F4:POSIX 路径**不得**折叠大小写(不同目录不许误匹
61
62
  // 空映射 = 恒等
62
63
  assert.equal(pathOf(applyPrefixMappings({ workspace: { path: '/home/Alice/proj/x' } }, [])), '/home/Alice/proj/x');
63
64
  });
65
+
66
+ /**
67
+ * #8 越界判定收敛:四份同义守卫(paths / restore 的 isWithinHome / restore 的 isRealInside /
68
+ * verify-recovery 的副本)合并为 isPathInside。三份旧实现用 `rel.startsWith('..')` 判越界,
69
+ * 会把名字真叫 `..foo` 的兄弟目录误判成逃逸(path.relative('/a/b', '/a/b/..foo') === '..foo')。
70
+ */
71
+ test('core-E1:越界判定只有一份实现,且 `..foo` 这种合法兄弟目录不得被误判成逃逸', () => {
72
+ const parent = path.resolve('sandbox', 'home');
73
+ const inside = (...segs: string[]): string => path.resolve(parent, ...segs);
74
+ const outside = path.resolve('sandbox', 'other');
75
+
76
+ // ① 名字真叫 ..foo 的兄弟目录在 parent 之内 —— 旧实现(rel.startsWith('..'))在此误杀
77
+ assert.equal(isPathInside(inside('..foo'), parent), true, '..foo 是子目录,不是 ..');
78
+ assert.equal(isPathInside(inside('..foo', 'settings.yaml'), parent), true);
79
+
80
+ // ② 等于父目录 / .. 折叠后仍在父目录内
81
+ assert.equal(isPathInside(parent, parent), true);
82
+ assert.equal(isPathInside(inside('a', '..', 'b'), parent), true);
83
+
84
+ // ③ 真越界:.. 段本身、以 .. + 分隔符开头、完全在外
85
+ assert.equal(isPathInside(inside('..'), parent), false);
86
+ assert.equal(isPathInside(inside('..', 'other'), parent), false);
87
+ assert.equal(isPathInside(outside, parent), false);
88
+
89
+ // ④ 别名与正典同口径(既有调用点不必改语义)
90
+ assert.equal(isSameOrChild(inside('..foo'), parent), true);
91
+ assert.equal(isSameOrChild(inside('..', 'x'), parent), false);
92
+
93
+ // ⑤ 大小写:缺省按平台(Windows 折叠、POSIX 不折叠),显式开关可覆盖
94
+ assert.equal(isPathInside(parent.toUpperCase(), parent), process.platform === 'win32');
95
+ assert.equal(isPathInside('/a/B', '/a/b', { foldCase: true }), true);
96
+ // foldCase:false 只在 POSIX 生效:win32 的 path.relative 自己就折大小写(故此处结果仍 true)
97
+ assert.equal(isPathInside('/a/B', '/a/b', { foldCase: false }), process.platform === 'win32');
98
+ });
@@ -41,14 +41,38 @@ export function isPathSafe(entryName: string): boolean {
41
41
  return true;
42
42
  }
43
43
 
44
- /** 候选目录是否位于父目录之内(含等于父目录)。
44
+ /** 越界判定选项。 */
45
+ export interface PathInsideOptions {
46
+ /**
47
+ * 比较前折叠大小写(Windows 文件系统大小写不敏感)。缺省按当前平台。
48
+ * 显式传 false 的场景:拿另一台机器的路径做形状判定(跨平台导入)。
49
+ */
50
+ foldCase?: boolean;
51
+ }
52
+
53
+ /** 候选路径是否位于父目录之内(含等于父目录)。
54
+ *
55
+ * 全仓**唯一**的越界判定(restore / verify-recovery / zip / recursive-walk / 路由都走这里):
56
+ * 早期四处各写一份,其中三份用 `rel.startsWith('..')` 判越界 —— 名字真的叫 `..foo` 的
57
+ * 兄弟目录会被误判为逃逸(`path.relative('/a/b','/a/b/..foo') === '..foo'`)。
58
+ * 越界只有两种形态:相对结果是 `..` 段本身,或以 `..` + 分隔符开头;绝对结果(跨盘符)同样越界。
45
59
  *
46
- * 纯字符串语义(不碰文件系统):两侧必须是**同一种拼写**,调用方若混用
47
- * realpath 结果与原路径(Windows 8.3 短名、macOS `/var`→`/private/var`)会误判为越界 ——
48
- * `path.relative` 不会折叠短名,务必先各自 realpath 再调用。 */
60
+ * 纯字符串语义(**不碰文件系统**):两侧各自 `path.resolve` 后比较。调用方若混用
61
+ * realpath 结果与原路径(Windows 8.3 短名、macOS `/var`→`/private/var`)仍会误判为越界 ——
62
+ * `path.resolve` 不折叠短名,真实路径那一层必须两侧都先 realpath 再调用。
63
+ */
64
+ export function isPathInside(child: string, parent: string, options: PathInsideOptions = {}): boolean {
65
+ const foldCase = options.foldCase ?? process.platform === 'win32';
66
+ const fold = (v: string): string => (foldCase ? v.toLowerCase() : v);
67
+ const rel = path.relative(fold(path.resolve(parent)), fold(path.resolve(child)));
68
+ if (rel === '') return true;
69
+ if (path.isAbsolute(rel)) return false; // 跨盘符(win32 relative 直接回绝对路径)
70
+ return rel !== '..' && !rel.startsWith(`..${path.sep}`);
71
+ }
72
+
73
+ /** 候选目录是否位于父目录之内(含等于父目录)—— `isPathInside` 的读法友好别名。 */
49
74
  export function isSameOrChild(p: string, parent: string): boolean {
50
- const rel = path.relative(parent, p);
51
- return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
75
+ return isPathInside(p, parent);
52
76
  }
53
77
 
54
78
  /**
@@ -0,0 +1,46 @@
1
+ /**
2
+ * #8 时间戳收敛:`src/utils/time.ts` 是唯一实现(此前同一串格式散在 12 处)。
3
+ * 这里钉住**形态**(定宽 / 仅 ASCII / 本地时区)与解析守卫(空 / 非有限 / 非法),
4
+ * 不钉调用点的回退文案(那是各处的产品口径)。
5
+ */
6
+ import test from 'node:test';
7
+ import assert from 'node:assert/strict';
8
+
9
+ import { formatDateOnly, formatDateStamp, formatMinuteStamp, parseDateInput } from './time.ts';
10
+
11
+ test('core-T1 三种形态:定宽、零填充、本地时区、仅 ASCII', () => {
12
+ const d = new Date(2026, 0, 5, 7, 8, 9); // 本地 2026-01-05 07:08:09
13
+ assert.equal(formatDateStamp(d), '20260105-070809');
14
+ assert.equal(formatDateOnly(d), '2026-01-05');
15
+ assert.equal(formatMinuteStamp(d), '2026-01-05 07:08');
16
+ // 定宽(导出文件名按字典序 = 时间序,靠的就是这个)
17
+ assert.equal(formatDateStamp(d).length, 15);
18
+ assert.equal(formatDateOnly(d).length, 10);
19
+ assert.equal(formatMinuteStamp(d).length, 16);
20
+ assert.match(formatDateStamp(d), /^[0-9]{8}-[0-9]{6}$/);
21
+
22
+ // 两位数边界:12 月 31 日 23:59:59 不得退化成一位
23
+ const edge = new Date(2026, 11, 31, 23, 59, 59);
24
+ assert.equal(formatDateStamp(edge), '20261231-235959');
25
+ assert.equal(formatMinuteStamp(edge), '2026-12-31 23:59');
26
+
27
+ // 缺省参数 = now(形态判定,不比对具体时刻)
28
+ assert.match(formatDateStamp(), /^[0-9]{8}-[0-9]{6}$/);
29
+ });
30
+
31
+ test('core-T2 parseDateInput:空 / 非有限 / 非法一律 null(不静默变 1970)', () => {
32
+ assert.equal(parseDateInput(null), null);
33
+ assert.equal(parseDateInput(undefined), null);
34
+ assert.equal(parseDateInput(''), null);
35
+ assert.equal(parseDateInput(' '), null);
36
+ assert.equal(parseDateInput(Number.NaN), null);
37
+ assert.equal(parseDateInput(Number.POSITIVE_INFINITY), null);
38
+ assert.equal(parseDateInput(Number.NEGATIVE_INFINITY), null);
39
+ assert.equal(parseDateInput('not-a-date'), null);
40
+ });
41
+
42
+ test('core-T3 parseDateInput:合法字符串与毫秒数照常解析(毫秒 0 不得被当成空)', () => {
43
+ assert.equal(parseDateInput('2026-01-05T07:08:09.000Z')?.toISOString(), '2026-01-05T07:08:09.000Z');
44
+ assert.equal(parseDateInput(0)?.getTime(), 0);
45
+ assert.equal(parseDateInput(1_767_593_289_000)?.getTime(), 1_767_593_289_000);
46
+ });