dsh-config-manager 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/lib/client.d.ts +33 -1
  2. package/lib/client.js +1060 -835
  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/migration-history.d.ts +28 -2
  10. package/lib/core/migration-history.js +41 -4
  11. package/lib/index.d.ts +2 -2
  12. package/lib/index.js +24 -6
  13. package/lib/routes/history.js +70 -5
  14. package/lib/routes/index.d.ts +1 -1
  15. package/lib/routes/kit.d.ts +2 -2
  16. package/lib/routes/messages.d.ts +1 -0
  17. package/lib/routes/messages.js +3 -0
  18. package/lib/sync/autosync-scheduler.js +6 -0
  19. package/lib/sync/backup-scheduler.js +6 -0
  20. package/lib/sync/ui-prefs.d.ts +8 -0
  21. package/lib/sync/ui-prefs.js +8 -0
  22. package/lib/utils/env-lock.d.ts +55 -1
  23. package/lib/utils/env-lock.js +131 -2
  24. package/lib/utils/messages-utils.d.ts +3 -0
  25. package/lib/utils/messages-utils.js +6 -0
  26. package/package.json +1 -1
  27. package/src/client/common/InfoHint.tsx +12 -3
  28. package/src/client/common/Skeleton.tsx +45 -8
  29. package/src/client/common/info-hint-guard.test.ts +196 -0
  30. package/src/client/common/routes.ts +3 -1
  31. package/src/client/common/skeleton-guard.test.ts +58 -0
  32. package/src/client/common/ui.tsx +17 -4
  33. package/src/client/config-manager.module.css +256 -27
  34. package/src/client/css-motion-guard.test.ts +230 -0
  35. package/src/client/environment/EnvironmentPanel.tsx +41 -29
  36. package/src/client/environment/maintenance/DiskUsageCard.tsx +28 -33
  37. package/src/client/environment/profiles-incomplete-ui.test.ts +9 -5
  38. package/src/client/export/ExportView.tsx +6 -6
  39. package/src/client/history/HistoryPanel.tsx +87 -2
  40. package/src/client/history/history-api.ts +49 -3
  41. package/src/client/history/history-locales.ts +30 -0
  42. package/src/client/home/HomePanel.tsx +55 -23
  43. package/src/client/market/MyConfigsWizard.tsx +12 -3
  44. package/src/client/recovery/RecoveryPanel.tsx +93 -92
  45. package/src/client/recovery/RollbackCard.tsx +25 -16
  46. package/src/client/sync/AutosyncCard.tsx +12 -6
  47. package/src/client/sync/ChannelConfigDialog.tsx +45 -45
  48. package/src/client/sync/DecryptPasswordCard.tsx +3 -3
  49. package/src/client/sync/SecurityOptionsCard.tsx +3 -3
  50. package/src/client/sync/SyncSectionPickerDialog.tsx +3 -3
  51. package/src/core/env-lock-lifecycle.ts +73 -0
  52. package/src/core/history-prune.test.ts +115 -0
  53. package/src/core/history-prune.ts +61 -0
  54. package/src/core/index.ts +2 -0
  55. package/src/core/migration-history.test.ts +78 -0
  56. package/src/core/migration-history.ts +46 -4
  57. package/src/index.ts +25 -6
  58. package/src/routes/history.ts +81 -4
  59. package/src/routes/index.ts +1 -1
  60. package/src/routes/kit.ts +2 -2
  61. package/src/routes/messages.ts +3 -0
  62. package/src/sync/autosync-scheduler.ts +3 -0
  63. package/src/sync/backup-scheduler.ts +3 -0
  64. package/src/sync/ui-prefs.test.ts +32 -0
  65. package/src/sync/ui-prefs.ts +16 -0
  66. package/src/utils/env-lock.test.ts +107 -0
  67. package/src/utils/env-lock.ts +124 -2
  68. package/src/utils/messages-utils.ts +6 -0
@@ -120,9 +120,9 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
120
120
  busy={busy}
121
121
  onPick={(cloneUrl) => { onFormChange({ repoUrl: cloneUrl }) }}
122
122
  />
123
- <label className={css.field}>
123
+ <div className={css.field}>
124
124
  <span className={css.fieldLabel}>{t('config.repoUrl')} <InfoHint text={t('config.repoUrlHint')} label={t('common.infoHint')} /></span>
125
- <input
125
+ <input aria-label={t('config.repoUrl')}
126
126
  type="text"
127
127
  className={css.input}
128
128
  value={repoUrl}
@@ -132,15 +132,15 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
132
132
  onFormChange({ repoUrl: e.target.value }) // 改动自动保存(防抖;关闭设置页不丢输入)
133
133
  }}
134
134
  />
135
- </label>
136
- <label className={css.field}>
135
+ </div>
136
+ <div className={css.field}>
137
137
  <span className={css.fieldLabel}>
138
138
  {t('config.token')}
139
139
  {' '}
140
140
  {statusInfo?.credentialConfigured === true && <Badge kind="ok">{t('config.tokenSaved')}</Badge>}
141
141
  <InfoHint text={t('config.tokenHint', { ref: SYNC_CREDENTIAL_REF })} label={t('common.infoHint')} />
142
142
  </span>
143
- <input
143
+ <input aria-label={t('config.token')}
144
144
  type="password"
145
145
  className={css.input}
146
146
  value={token}
@@ -151,7 +151,7 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
151
151
  onFormChange({ token: e.target.value })
152
152
  }}
153
153
  />
154
- </label>
154
+ </div>
155
155
 
156
156
  {/* GitHub OAuth 登录(device flow):弹窗内仅 git 通道显示;已登录(token 有效)时整块隐藏 */}
157
157
  {githubSignedIn === false && (
@@ -217,9 +217,9 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
217
217
  />
218
218
  <InfoHint text={t('webdav.presetHint')} label={t('common.infoHint')} />
219
219
  </div>
220
- <label className={css.field}>
220
+ <div className={css.field}>
221
221
  <span className={css.fieldLabel}>{t('webdav.url')} <InfoHint text={t('webdav.urlHint')} label={t('common.infoHint')} /></span>
222
- <input
222
+ <input aria-label={t('webdav.url')}
223
223
  type="text"
224
224
  className={css.input}
225
225
  value={webdavUrl}
@@ -229,8 +229,8 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
229
229
  onFormChange({ webdavUrl: e.target.value })
230
230
  }}
231
231
  />
232
- </label>
233
- <label className={css.field}>
232
+ </div>
233
+ <div className={css.field}>
234
234
  <span className={css.fieldLabel}>
235
235
  {t('webdav.username')}
236
236
  {' '}
@@ -238,7 +238,7 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
238
238
  {' '}
239
239
  <InfoHint text={t('webdav.usernameHint')} label={t('common.infoHint')} />
240
240
  </span>
241
- <input
241
+ <input aria-label={t('webdav.username')}
242
242
  type="text"
243
243
  className={css.input}
244
244
  value={webdavUsername}
@@ -249,15 +249,15 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
249
249
  onFormChange({ webdavUsername: e.target.value })
250
250
  }}
251
251
  />
252
- </label>
253
- <label className={css.field}>
252
+ </div>
253
+ <div className={css.field}>
254
254
  <span className={css.fieldLabel}>
255
255
  {t('webdav.password')}
256
256
  {' '}
257
257
  {statusInfo?.webdav?.passwordConfigured === true && <Badge kind="ok">{t('webdav.passwordSaved')}</Badge>}
258
258
  <InfoHint text={t('webdav.passwordHint', { ref: SYNC_WEBDAV_CREDENTIAL_REF })} label={t('common.infoHint')} />
259
259
  </span>
260
- <input
260
+ <input aria-label={t('webdav.password')}
261
261
  type="password"
262
262
  className={css.input}
263
263
  value={webdavPassword}
@@ -268,7 +268,7 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
268
268
  onFormChange({ webdavPassword: e.target.value })
269
269
  }}
270
270
  />
271
- </label>
271
+ </div>
272
272
  </>
273
273
  )}
274
274
 
@@ -287,9 +287,9 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
287
287
  />
288
288
  <InfoHint text={t('cloud.providerHint')} label={t('common.infoHint')} />
289
289
  </div>
290
- <label className={css.field}>
290
+ <div className={css.field}>
291
291
  <span className={css.fieldLabel}>{t('cloud.endpoint')} <InfoHint text={t('cloud.endpointHint')} label={t('common.infoHint')} /></span>
292
- <input
292
+ <input aria-label={t('cloud.endpoint')}
293
293
  type="text"
294
294
  className={css.input}
295
295
  value={s3Endpoint}
@@ -297,10 +297,10 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
297
297
  disabled={busy}
298
298
  onChange={(e: ChangeEvent<HTMLInputElement>) => { onFormChange({ s3Endpoint: e.target.value }) }}
299
299
  />
300
- </label>
301
- <label className={css.field}>
300
+ </div>
301
+ <div className={css.field}>
302
302
  <span className={css.fieldLabel}>{t('cloud.region')} <InfoHint text={t('cloud.regionHint')} label={t('common.infoHint')} /></span>
303
- <input
303
+ <input aria-label={t('cloud.region')}
304
304
  type="text"
305
305
  className={css.input}
306
306
  value={s3Region}
@@ -308,10 +308,10 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
308
308
  disabled={busy}
309
309
  onChange={(e: ChangeEvent<HTMLInputElement>) => { onFormChange({ s3Region: e.target.value }) }}
310
310
  />
311
- </label>
312
- <label className={css.field}>
311
+ </div>
312
+ <div className={css.field}>
313
313
  <span className={css.fieldLabel}>{t('cloud.bucket')} <InfoHint text={t('cloud.bucketHint')} label={t('common.infoHint')} /></span>
314
- <input
314
+ <input aria-label={t('cloud.bucket')}
315
315
  type="text"
316
316
  className={css.input}
317
317
  value={s3Bucket}
@@ -319,10 +319,10 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
319
319
  disabled={busy}
320
320
  onChange={(e: ChangeEvent<HTMLInputElement>) => { onFormChange({ s3Bucket: e.target.value }) }}
321
321
  />
322
- </label>
323
- <label className={css.field}>
322
+ </div>
323
+ <div className={css.field}>
324
324
  <span className={css.fieldLabel}>{t('cloud.prefix')} <InfoHint text={t('cloud.prefixHint')} label={t('common.infoHint')} /></span>
325
- <input
325
+ <input aria-label={t('cloud.prefix')}
326
326
  type="text"
327
327
  className={css.input}
328
328
  value={s3Prefix}
@@ -330,10 +330,10 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
330
330
  disabled={busy}
331
331
  onChange={(e: ChangeEvent<HTMLInputElement>) => { onFormChange({ s3Prefix: e.target.value }) }}
332
332
  />
333
- </label>
334
- <label className={css.field}>
333
+ </div>
334
+ <div className={css.field}>
335
335
  <span className={css.fieldLabel}>{t('cloud.accessKeyId')} <InfoHint text={t('cloud.accessKeyIdHint')} label={t('common.infoHint')} /></span>
336
- <input
336
+ <input aria-label={t('cloud.accessKeyId')}
337
337
  type="text"
338
338
  className={css.input}
339
339
  value={s3AccessKeyId}
@@ -342,7 +342,7 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
342
342
  disabled={busy}
343
343
  onChange={(e: ChangeEvent<HTMLInputElement>) => { onFormChange({ s3AccessKeyId: e.target.value }) }}
344
344
  />
345
- </label>
345
+ </div>
346
346
  <div className={css.controlRow}>
347
347
  <Checkbox
348
348
  checked={s3PathStyle}
@@ -352,14 +352,14 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
352
352
  />
353
353
  <InfoHint text={t('cloud.pathStyleHint')} label={t('common.infoHint')} />
354
354
  </div>
355
- <label className={css.field}>
355
+ <div className={css.field}>
356
356
  <span className={css.fieldLabel}>
357
357
  {t('cloud.secret')}
358
358
  {' '}
359
359
  {statusInfo?.s3?.secretStored === true && <Badge kind="ok">{t('cloud.secretSaved')}</Badge>}
360
360
  <InfoHint text={t('cloud.secretHint', { ref: cloudSecretRef })} label={t('common.infoHint')} />
361
361
  </span>
362
- <input
362
+ <input aria-label={t('cloud.secret')}
363
363
  type="password"
364
364
  className={css.input}
365
365
  value={s3Secret}
@@ -368,7 +368,7 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
368
368
  disabled={busy}
369
369
  onChange={(e: ChangeEvent<HTMLInputElement>) => { onFormChange({ s3Secret: e.target.value }) }}
370
370
  />
371
- </label>
371
+ </div>
372
372
  </>
373
373
  )}
374
374
 
@@ -378,9 +378,9 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
378
378
  {/* G-34:gist 刻意不外置 blob(一次 GET 全量 / 单文件超限截断 / 文件数上限)⇒ 大分区不适合走 gist;
379
379
  该说明属机制类,收进标题 ⓘ(2026-10-12 用户要求) */}
380
380
  <span className={css.groupLabel}>{t('cloud.gistTitle')} <InfoHint text={t(GIST_LARGE_SECTION_HINT_KEY)} label={t('common.infoHint')} /></span>
381
- <label className={css.field}>
381
+ <div className={css.field}>
382
382
  <span className={css.fieldLabel}>{t('cloud.gistId')} <InfoHint text={t('cloud.gistIdHint')} label={t('common.infoHint')} /></span>
383
- <input
383
+ <input aria-label={t('cloud.gistId')}
384
384
  type="text"
385
385
  className={css.input}
386
386
  value={gistId}
@@ -389,10 +389,10 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
389
389
  disabled={busy}
390
390
  onChange={(e: ChangeEvent<HTMLInputElement>) => { onFormChange({ gistId: e.target.value }) }}
391
391
  />
392
- </label>
393
- <label className={css.field}>
392
+ </div>
393
+ <div className={css.field}>
394
394
  <span className={css.fieldLabel}>{t('cloud.apiBaseUrl')} <InfoHint text={t('cloud.apiBaseUrlHint')} label={t('common.infoHint')} /></span>
395
- <input
395
+ <input aria-label={t('cloud.apiBaseUrl')}
396
396
  type="text"
397
397
  className={css.input}
398
398
  value={gistApiBaseUrl}
@@ -400,10 +400,10 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
400
400
  disabled={busy}
401
401
  onChange={(e: ChangeEvent<HTMLInputElement>) => { onFormChange({ gistApiBaseUrl: e.target.value }) }}
402
402
  />
403
- </label>
404
- <label className={css.field}>
403
+ </div>
404
+ <div className={css.field}>
405
405
  <span className={css.fieldLabel}>{t('cloud.filePrefix')} <InfoHint text={t('cloud.filePrefixHint')} label={t('common.infoHint')} /></span>
406
- <input
406
+ <input aria-label={t('cloud.filePrefix')}
407
407
  type="text"
408
408
  className={css.input}
409
409
  value={gistFilePrefix}
@@ -411,15 +411,15 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
411
411
  disabled={busy}
412
412
  onChange={(e: ChangeEvent<HTMLInputElement>) => { onFormChange({ gistFilePrefix: e.target.value }) }}
413
413
  />
414
- </label>
415
- <label className={css.field}>
414
+ </div>
415
+ <div className={css.field}>
416
416
  <span className={css.fieldLabel}>
417
417
  {t('cloud.token')}
418
418
  {' '}
419
419
  {statusInfo?.gist?.secretStored === true && <Badge kind="ok">{t('cloud.tokenSaved')}</Badge>}
420
420
  <InfoHint text={t('cloud.tokenHint', { ref: cloudSecretRef })} label={t('common.infoHint')} />
421
421
  </span>
422
- <input
422
+ <input aria-label={t('cloud.token')}
423
423
  type="password"
424
424
  className={css.input}
425
425
  value={gistToken}
@@ -428,7 +428,7 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
428
428
  disabled={busy}
429
429
  onChange={(e: ChangeEvent<HTMLInputElement>) => { onFormChange({ gistToken: e.target.value }) }}
430
430
  />
431
- </label>
431
+ </div>
432
432
  </>
433
433
  )}
434
434
 
@@ -22,9 +22,9 @@ export function DecryptPasswordCard({ t, settings, onPatchSettings, onPersistDec
22
22
  }) {
23
23
  return (
24
24
  <Card>
25
- <label className={css.field}>
25
+ <div className={css.field}>
26
26
  <span className={css.fieldLabel}>{t('mode.decryptPassword')} <InfoHint text={t('mode.decryptPasswordHint')} label={t('common.infoHint')} /></span>
27
- <input
27
+ <input aria-label={t('mode.decryptPassword')}
28
28
  type="password"
29
29
  className={css.input}
30
30
  value={settings.decryptPassword}
@@ -33,7 +33,7 @@ export function DecryptPasswordCard({ t, settings, onPatchSettings, onPersistDec
33
33
  onChange={(e: ChangeEvent<HTMLInputElement>) => { onPatchSettings({ decryptPassword: e.target.value }) }}
34
34
  onBlur={onPersistDecryptPassword}
35
35
  />
36
- </label>
36
+ </div>
37
37
  {settings.decryptPasswordSaved && (
38
38
  <div className={css.actionRow}>
39
39
  <Badge kind="ok">{t('mode.decryptPasswordSaved')}</Badge>
@@ -47,13 +47,13 @@ export function SecurityOptionsCard({ t, settings, onToggleEncrypt, onToggleIncl
47
47
  )}
48
48
  {settings.encrypt && (
49
49
  <div className={css.secretFields}>
50
- <label className={css.field}>
50
+ <div className={css.field}>
51
51
  <span className={css.fieldLabel}>
52
52
  {t('mode.password')}
53
53
  {' '}
54
54
  {settings.encryptPasswordSaved && <InfoHint text={t('mode.passwordSavedHint')} label={t('common.infoHint')} />}
55
55
  </span>
56
- <input
56
+ <input aria-label={t('mode.password')}
57
57
  type="password"
58
58
  className={css.input}
59
59
  value={settings.encryptPassword}
@@ -63,7 +63,7 @@ export function SecurityOptionsCard({ t, settings, onToggleEncrypt, onToggleIncl
63
63
  // 失焦即落库(两个框一致才写)——用户不必手动保存,下次留空即沿用
64
64
  onBlur={onPersistEncryptPassword}
65
65
  />
66
- </label>
66
+ </div>
67
67
  <label className={css.field}>
68
68
  <span className={css.fieldLabel}>{t('mode.passwordConfirm')}</span>
69
69
  <input
@@ -157,9 +157,9 @@ export function SyncSectionPickerDialog({ open, t, cmT, uiT, sectionName, catalo
157
157
  Checkbox 内部是 label 元素,把输入控件放进去会让点输入框也切换勾选。 */}
158
158
  {s.id === 'sessions' && sections.includes('sessions') && (
159
159
  <div className={css.field}>
160
- <label className={css.field}>
160
+ <div className={css.field}>
161
161
  <span className={css.fieldLabel}>{t('mode.sessionsLimit')} <InfoHint text={t('mode.sessionsLimitHint')} label={t('common.infoHint')} /></span>
162
- <input
162
+ <input aria-label={t('mode.sessionsLimit')}
163
163
  type="number"
164
164
  min={0}
165
165
  max={10000}
@@ -169,7 +169,7 @@ export function SyncSectionPickerDialog({ open, t, cmT, uiT, sectionName, catalo
169
169
  onSessionsLimit(e.target.value === '' ? DEFAULT_SYNC_SESSIONS_LIMIT : Number(e.target.value))
170
170
  }}
171
171
  />
172
- </label>
172
+ </div>
173
173
  <div className={css.actionRowTop}>
174
174
  <Button size="sm" onClick={() => { setView('sessions') }}>{t('mode.sessionsPick')}</Button>
175
175
  {sessionsInclude.length > 0 && (
@@ -0,0 +1,73 @@
1
+ /**
2
+ * 环境锁的**生命周期自愈**(与 acquire/release 语义分开,避免污染 env-lock.ts 的核心不变量)。
3
+ *
4
+ * 三件事:
5
+ * ① 启动时回收「结构性可证」的 stale 残留锁(owner 确证死亡 / PID 复用),并把交给 SAFE MODE 判定的
6
+ * 锁状态按回收结果修正;
7
+ * ② 启动时清掉孤儿心跳 sidecar(已不是持有者、心跳也早已停更的垃圾);
8
+ * ③ 进程退出时**同步**释放本实例持有的锁('exit' 里不能 await,所以必须同步 fs)。
9
+ *
10
+ * 为什么只在分类 NORMAL 时做 ①②:RECOVERY_REQUIRED / NEEDS_ATTENTION 意味着有未决事务,此时删掉
11
+ * ownership 等于替用户抹掉事故现场(journal↔ownership binding 也会失去对照证据)——那类必须显式恢复。
12
+ * 为什么不碰 corrupt 残留与「心跳长过期」启发式:`reclaimProvableStaleLock` 只认结构性可证;
13
+ * 其余留给显式回收(`--recover-stale-lock` / GUI 事故恢复),否则在拿不到 OS identity 的机器上会误删活锁。
14
+ *
15
+ * 真机成因与量化数据 → `docs/lessons/recovery-console.md`;规则 → `AGENTS.md`「备份 / 恢复 / 回滚点」。
16
+ */
17
+ import type { EnvironmentLockManager, LockState } from '../utils/env-lock.ts'
18
+ import { mapLockStateForStartup } from './phase3-host.ts'
19
+ import { utilsMsg } from '../utils/messages-utils.ts'
20
+
21
+ /** 交给 `resolveStartupSafeMode` 的锁状态口径(与 `mapLockStateForStartup` 同一来源,不另立枚举)。 */
22
+ export type StartupLockState = ReturnType<typeof mapLockStateForStartup>
23
+
24
+ /** 只要求 info/warn(宿主 logger 结构兼容;测试用假 logger 即可)。 */
25
+ export interface LockLifecycleLog {
26
+ info(message: string): void
27
+ warn(message: string): void
28
+ }
29
+
30
+ /** 自愈只碰这三个动作,不把整个 manager 传进来(也就无法顺手 acquire/validate)。 */
31
+ type LockLifecyclePort = Pick<EnvironmentLockManager, 'reclaimProvableStaleLock' | 'cleanupOrphanHeartbeats' | 'releaseOnExitSync'>
32
+
33
+ /**
34
+ * 启动自愈:回收可证 stale 残留锁 + 清孤儿心跳,返回应当交给 SAFE MODE 判定的锁状态。
35
+ *
36
+ * 回收成功后返回 `'FREE'`:否则「无活锁者」的陈旧标记不会被一并复位,本会话的写操作会继续被 423 挡着
37
+ * (界面却说没有待处理事项)。回收被拒(证明不出已死)时原样返回,只记一条 warn。
38
+ */
39
+ export async function reclaimStaleLockAtStartup(input: {
40
+ kind: string
41
+ inspected: LockState
42
+ lock: LockLifecyclePort
43
+ log: LockLifecycleLog
44
+ }): Promise<StartupLockState> {
45
+ let lockState = mapLockStateForStartup(input.inspected)
46
+ if (input.kind === 'NORMAL' && input.inspected === 'STALE_LOCK_DETECTED') {
47
+ const reclaimed = await input.lock.reclaimProvableStaleLock().catch(() => null)
48
+ if (reclaimed !== null && reclaimed.ok) {
49
+ lockState = 'FREE'
50
+ input.log.info(utilsMsg('utils.envLock.autoReclaimedStale', {
51
+ op: reclaimed.removedOwner?.op ?? 'unknown',
52
+ pid: reclaimed.removedOwner?.pid ?? 0,
53
+ }))
54
+ } else if (reclaimed !== null) {
55
+ input.log.warn(`残留锁自动回收被拒(保留现场,走显式回收):${reclaimed.detail ?? ''}`)
56
+ }
57
+ }
58
+ if (input.kind === 'NORMAL') {
59
+ const orphaned = await input.lock.cleanupOrphanHeartbeats().catch(() => 0)
60
+ if (orphaned > 0) input.log.info(utilsMsg('utils.envLock.orphanHeartbeatsRemoved', { count: orphaned }))
61
+ }
62
+ return lockState
63
+ }
64
+
65
+ /**
66
+ * 生成退出释放钩子:只删**本实例 instanceId** 的 ownership 与心跳(与 `release()` 同一不变量),永不抛。
67
+ * 调用方负责 `process.once('exit', fn)` 与 dispose 时摘钩。
68
+ */
69
+ export function createExitLockReleaser(lock: Pick<EnvironmentLockManager, 'releaseOnExitSync'>): () => void {
70
+ return () => {
71
+ try { lock.releaseOnExitSync() } catch { /* 退出路径不许抛 */ }
72
+ }
73
+ }
@@ -0,0 +1,115 @@
1
+ import { test } from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { createHistoryPruner } from './history-prune.ts'
4
+
5
+ /** 记录调用的假 store:默认删除「多余」条目,返回被删数量。 */
6
+ function fakeHistory(behaviour: 'ok' | 'throw' = 'ok') {
7
+ const calls: number[] = []
8
+ return {
9
+ calls,
10
+ async retention(limit: number): Promise<string[]> {
11
+ calls.push(limit)
12
+ if (behaviour === 'throw') throw new Error('EACCES')
13
+ return ['a.json', 'b.json'].slice(0, Math.max(0, limit - 1))
14
+ },
15
+ }
16
+ }
17
+
18
+ function fakeLog() {
19
+ const info: Array<{ message: string; meta?: Record<string, unknown> }> = []
20
+ const warn: Array<{ message: string; meta?: Record<string, unknown> }> = []
21
+ return {
22
+ info,
23
+ warn,
24
+ logger: {
25
+ info: (message: string, meta?: Record<string, unknown>) => { info.push({ message, ...(meta ? { meta } : {}) }) },
26
+ warn: (message: string, meta?: Record<string, unknown>) => { warn.push({ message, ...(meta ? { meta } : {}) }) },
27
+ },
28
+ }
29
+ }
30
+
31
+ test('启动触发:按配置上限清理一次并写日志;0 = 不限制时一次都不删', async () => {
32
+ const history = fakeHistory()
33
+ const { logger, info } = fakeLog()
34
+ const prune = createHistoryPruner({ history, log: logger, readRetentionLimit: async () => 3 })
35
+ await prune('startup')
36
+ assert.deepEqual(history.calls, [3], '启动应清一次,且用配置值')
37
+ assert.equal(info.length, 1, '删掉了条目就要留一条日志')
38
+ assert.equal(info[0]?.message, '迁移历史自动清理')
39
+ assert.deepEqual(info[0]?.meta, { maxEntries: 3, removed: 2 })
40
+
41
+ const unlimited = fakeHistory()
42
+ const second = fakeLog()
43
+ const pruneUnlimited = createHistoryPruner({ history: unlimited, log: second.logger, readRetentionLimit: async () => 0 })
44
+ await pruneUnlimited('startup')
45
+ assert.deepEqual(unlimited.calls, [], '0 = 不限制 ⇒ 绝不批量删')
46
+ assert.equal(second.info.length, 0)
47
+ })
48
+
49
+ test('非法配置回落缺省 1000(不因手改 ui-prefs 把历史全删)', async () => {
50
+ const history = fakeHistory()
51
+ const { logger } = fakeLog()
52
+ const prune = createHistoryPruner({ history, log: logger, readRetentionLimit: async () => '1000' })
53
+ await prune('startup')
54
+ assert.deepEqual(history.calls, [1000], '字符串等非法值必须回落 DEFAULT_MIGRATION_RETENTION')
55
+ })
56
+
57
+ test('写入触发按 60 s 节流:紧接着的第二次 append 跳过,窗口过后再放行', async () => {
58
+ const history = fakeHistory()
59
+ const { logger } = fakeLog()
60
+ let clock = 1_000_000
61
+ const prune = createHistoryPruner({ history, log: logger, readRetentionLimit: async () => 5, now: () => clock })
62
+ await prune('startup')
63
+ await prune('append')
64
+ assert.deepEqual(history.calls, [5], '刚启动清理过 ⇒ 紧随的 append 落在节流窗口内');
65
+ clock += 61_000
66
+ await prune('append')
67
+ assert.deepEqual(history.calls, [5, 5], '窗口过后 append 应执行')
68
+ })
69
+
70
+ test('防重入:并发调用只有一次真正执行', async () => {
71
+ const calls: number[] = []
72
+ let release!: () => void
73
+ const gate = new Promise<void>((resolve) => { release = resolve })
74
+ const history = {
75
+ calls,
76
+ async retention(limit: number): Promise<string[]> {
77
+ calls.push(limit)
78
+ await gate
79
+ return []
80
+ },
81
+ }
82
+ const prune = createHistoryPruner({ history, log: fakeLog().logger, readRetentionLimit: async () => 2, now: () => 0 })
83
+ const first = prune('startup')
84
+ const second = prune('append')
85
+ await second
86
+ assert.deepEqual(calls, [2], '在飞期间不得并发再删一遍')
87
+ release()
88
+ await first
89
+ })
90
+
91
+ test('失败只进日志、绝不抛错(清理失败不能拖垮历史写入)', async () => {
92
+ const history = fakeHistory('throw')
93
+ const { logger, warn, info } = fakeLog()
94
+ const prune = createHistoryPruner({ history, log: logger, readRetentionLimit: async () => 10 })
95
+ await prune('startup')
96
+ assert.equal(info.length, 0)
97
+ assert.equal(warn.length, 1)
98
+ assert.equal(warn[0]?.message, '迁移历史自动清理失败')
99
+ assert.match(String(warn[0]?.meta?.['error']), /EACCES/)
100
+ })
101
+
102
+ test('读配置本身失败也走 warn 分支(ui-prefs 读不出不阻塞后续触发)', async () => {
103
+ const history = fakeHistory()
104
+ const { logger, warn } = fakeLog()
105
+ let attempts = 0
106
+ const prune = createHistoryPruner({
107
+ history,
108
+ log: logger,
109
+ readRetentionLimit: async () => { attempts += 1; if (attempts === 1) throw new Error('boom'); return 4 },
110
+ })
111
+ await prune('startup')
112
+ assert.equal(warn.length, 1)
113
+ await prune('startup')
114
+ assert.deepEqual(history.calls, [4], '下一次触发应恢复正常(inFlight 已复位)')
115
+ })
@@ -0,0 +1,61 @@
1
+ /**
2
+ * 迁移历史自动清理的调度器(宿主只做接线,逻辑留在这里)。
3
+ *
4
+ * 为什么单独成文件:src/index.ts 有体量棘轮(tests/file-size-ratchet.test.ts),
5
+ * 而这段调度与 HTTP 路由无关 —— 只依赖「历史 store + ui-prefs 策略 + 日志」三件事。
6
+ *
7
+ * 语义:保留上限 = ui-prefs.json 的 historyRetentionMaxEntries(缺省 1000;0 = 不限制,绝不批量删)。
8
+ * 触发:启动后一次 + 每次历史写入成功后(写入触发按 intervalMs 节流;同时只跑一个)。
9
+ * **不写审计条目**:清理本身若进历史,则「保留最近 N 条」永远差一条,每次写入都会再删再写
10
+ * (自反馈 churn);因此清理只删最旧文件,结果只进宿主日志。
11
+ */
12
+ import { resolveHistoryRetention, type MigrationStore } from './migration-history.ts'
13
+
14
+ /** 只用到 retention;收窄依赖便于单测替身。 */
15
+ export type HistoryPruneStore = Pick<MigrationStore, 'retention'>
16
+
17
+ export interface HistoryPruneLogger {
18
+ info(message: string, meta?: Record<string, unknown>): void
19
+ warn(message: string, meta?: Record<string, unknown>): void
20
+ }
21
+
22
+ export interface HistoryPrunerOptions {
23
+ history: HistoryPruneStore
24
+ /**
25
+ * 读取用户配置的保留上限(原值,非法由 resolveHistoryRetention 归一)。
26
+ * 由宿主注入:core 层不得 import ../sync/*(tests/architecture-boundaries.test.ts)。
27
+ */
28
+ readRetentionLimit: () => Promise<unknown>
29
+ log: HistoryPruneLogger
30
+ /** 写入触发的节流窗口(缺省 60 s);启动触发不受它影响。 */
31
+ intervalMs?: number
32
+ /** 注入时钟(测试用)。 */
33
+ now?: () => number
34
+ }
35
+
36
+ export type HistoryPruneTrigger = 'startup' | 'append'
37
+
38
+ /** 返回 pruneHistory(trigger):fire-and-forget 调用,永不抛错(失败只进日志)。 */
39
+ export function createHistoryPruner(options: HistoryPrunerOptions): (trigger: HistoryPruneTrigger) => Promise<void> {
40
+ const { history, readRetentionLimit, log, intervalMs = 60_000, now = Date.now } = options
41
+ let inFlight = false
42
+ let lastAt = 0
43
+ return async function pruneHistory(trigger: HistoryPruneTrigger): Promise<void> {
44
+ if (inFlight) return
45
+ const at = now()
46
+ // 节流只压「写入触发」:lastAt 由上一次实际执行决定,启动那一次基本总是放行。
47
+ if (trigger === 'append' && at - lastAt < intervalMs) return
48
+ inFlight = true
49
+ lastAt = at
50
+ try {
51
+ const limit = resolveHistoryRetention(await readRetentionLimit())
52
+ if (limit <= 0) return
53
+ const removed = await history.retention(limit)
54
+ if (removed.length > 0) log.info('迁移历史自动清理', { maxEntries: limit, removed: removed.length })
55
+ } catch (error) {
56
+ log.warn('迁移历史自动清理失败', { error: error instanceof Error ? error.message : String(error) })
57
+ } finally {
58
+ inFlight = false
59
+ }
60
+ }
61
+ }
package/src/core/index.ts CHANGED
@@ -52,6 +52,8 @@ export {
52
52
  parseHistoryQuery, isValidMigrationKind, redactHistoryText,
53
53
  makeHistoryFilename, isHistoryBasename, MIGRATION_HISTORY_DIR,
54
54
  DEFAULT_MIGRATION_RETENTION, MIGRATION_HISTORY_SCHEMA_VERSION,
55
+ HISTORY_RETENTION_MIN, HISTORY_RETENTION_MAX,
56
+ isValidHistoryRetention, resolveHistoryRetention,
55
57
  type MigrationKind, type MigrationResult, type MigrationHistoryEntry,
56
58
  type StoredMigrationHistoryEntry, type MigrationQuery, type MigrationHistoryStats,
57
59
  type ExportFormat, type ReadMigrationResult, type AppendResult, type MigrationIo,