dsh-config-manager 0.4.1 → 0.4.3

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 (131) hide show
  1. package/README.md +14 -0
  2. package/lib/cli/actions.js +2 -3
  3. package/lib/cli/import-source.js +2 -6
  4. package/lib/cli/index.js +2 -3
  5. package/lib/client.d.ts +5 -5
  6. package/lib/client.js +26250 -25872
  7. package/lib/core/access-mode.d.ts +25 -0
  8. package/lib/core/access-mode.js +28 -0
  9. package/lib/core/exporter.js +2 -4
  10. package/lib/core/host-schedulers/cache-cleanup.d.ts +41 -0
  11. package/lib/core/host-schedulers/cache-cleanup.js +45 -0
  12. package/lib/core/host-schedulers/lifecycle-hooks.d.ts +51 -0
  13. package/lib/core/host-schedulers/lifecycle-hooks.js +78 -0
  14. package/lib/core/host-schedulers/market-cache.d.ts +40 -0
  15. package/lib/core/host-schedulers/market-cache.js +92 -0
  16. package/lib/core/model-tools.js +2 -6
  17. package/lib/core/restore.d.ts +0 -2
  18. package/lib/core/restore.js +16 -18
  19. package/lib/core/verify-recovery.js +4 -7
  20. package/lib/index.d.ts +3 -22
  21. package/lib/index.js +74 -330
  22. package/lib/profiles/dsh-profile-manager.d.ts +23 -1
  23. package/lib/profiles/dsh-profile-manager.js +70 -2
  24. package/lib/routes/kit.d.ts +61 -1
  25. package/lib/routes/kit.js +72 -3
  26. package/lib/routes/prefs.js +6 -6
  27. package/lib/routes/recovery.js +25 -41
  28. package/lib/routes/request-trust.d.ts +28 -0
  29. package/lib/routes/request-trust.js +65 -0
  30. package/lib/routes/route-support.d.ts +23 -1
  31. package/lib/routes/route-support.js +185 -0
  32. package/lib/routes/snapshots.js +4 -11
  33. package/lib/routes/sync.js +5 -7
  34. package/lib/security/redaction.d.ts +5 -1
  35. package/lib/security/redaction.js +26 -23
  36. package/lib/sync/backup-scheduler.js +2 -6
  37. package/lib/ui/backup-inspect.d.ts +1 -1
  38. package/lib/ui/dsh-profiles-view.d.ts +0 -10
  39. package/lib/ui/dsh-profiles-view.js +3 -7
  40. package/lib/ui/snapshots-view.d.ts +0 -14
  41. package/lib/ui/snapshots-view.js +16 -2
  42. package/lib/utils/paths.d.ts +20 -4
  43. package/lib/utils/paths.js +22 -6
  44. package/lib/utils/time.d.ts +31 -0
  45. package/lib/utils/time.js +54 -0
  46. package/package.json +1 -1
  47. package/src/cli/actions.ts +2 -3
  48. package/src/cli/import-source.ts +2 -7
  49. package/src/cli/index.ts +2 -3
  50. package/src/client/about/AboutPanel.tsx +8 -1
  51. package/src/client/about/ReleaseBody.tsx +22 -52
  52. package/src/client/about/ReleaseNotesDialog.tsx +15 -69
  53. package/src/client/about/release-notes-view.ts +4 -11
  54. package/src/client/common/access-mode.ts +21 -0
  55. package/src/client/common/info-hint-guard.test.ts +11 -5
  56. package/src/client/common/ui.tsx +23 -0
  57. package/src/client/config-manager.module.css +201 -32
  58. package/src/client/css-token-guard.test.ts +135 -1
  59. package/src/client/home/HomePanel.tsx +31 -6
  60. package/src/client/import/ConflictList.tsx +3 -3
  61. package/src/client/import/ImportWizardView.tsx +1 -1
  62. package/src/client/library/ArtifactRow.tsx +2 -2
  63. package/src/client/library/RestorePlanView.tsx +21 -9
  64. package/src/client/library/report-dismiss.test.ts +5 -3
  65. package/src/client/locales/about.ts +103 -0
  66. package/src/client/locales/backup.ts +141 -0
  67. package/src/client/locales/common.ts +113 -0
  68. package/src/client/locales/export.ts +184 -0
  69. package/src/client/locales/foreign.ts +184 -0
  70. package/src/client/locales/import-compat.ts +32 -0
  71. package/src/client/locales/import.ts +192 -0
  72. package/src/client/locales/next-steps.ts +25 -0
  73. package/src/client/locales/overview-control.ts +32 -0
  74. package/src/client/locales/overview.ts +153 -0
  75. package/src/client/locales/profiles.ts +263 -0
  76. package/src/client/locales/report.ts +17 -0
  77. package/src/client/locales/restore.ts +132 -0
  78. package/src/client/locales/sessions.ts +257 -0
  79. package/src/client/locales/shell.ts +149 -0
  80. package/src/client/locales.ts +49 -1783
  81. package/src/client/market/MarketImportReview.tsx +2 -2
  82. package/src/client/market/MarketPanel.tsx +1 -1
  83. package/src/client/market/market-view.ts +3 -5
  84. package/src/client/recovery/RecoveryPanel.tsx +62 -1054
  85. package/src/client/recovery/SessionHealthCard.tsx +134 -0
  86. package/src/client/recovery/SessionHealthDialog.tsx +665 -0
  87. package/src/client/recovery/SessionLayoutSection.tsx +284 -0
  88. package/src/client/recovery/recovery-api.ts +10 -1
  89. package/src/client/recovery/recovery-panel-layout.test.ts +20 -5
  90. package/src/client/recovery/session-dialog-mount.test.ts +16 -9
  91. package/src/client/recovery/use-recovery-write.test.ts +90 -0
  92. package/src/client/recovery/use-recovery-write.ts +53 -0
  93. package/src/client/run-store.ts +57 -2
  94. package/src/client/sync/PushPreviewCard.tsx +2 -2
  95. package/src/client/sync/SyncConfirmView.tsx +5 -5
  96. package/src/client/sync/SyncLogList.tsx +2 -2
  97. package/src/client/sync/history-model.ts +4 -5
  98. package/src/client/sync/sync-view.ts +3 -4
  99. package/src/core/access-mode.ts +37 -0
  100. package/src/core/exporter.ts +2 -4
  101. package/src/core/host-schedulers/cache-cleanup.test.ts +84 -0
  102. package/src/core/host-schedulers/cache-cleanup.ts +74 -0
  103. package/src/core/host-schedulers/lifecycle-hooks.test.ts +111 -0
  104. package/src/core/host-schedulers/lifecycle-hooks.ts +118 -0
  105. package/src/core/host-schedulers/market-cache.test.ts +93 -0
  106. package/src/core/host-schedulers/market-cache.ts +116 -0
  107. package/src/core/model-tools.ts +2 -7
  108. package/src/core/restore-failure-state.test.ts +210 -0
  109. package/src/core/restore.ts +16 -18
  110. package/src/core/verify-recovery.ts +4 -7
  111. package/src/index.ts +81 -335
  112. package/src/profiles/dsh-profile-copy-rollback.test.ts +156 -0
  113. package/src/profiles/dsh-profile-manager.ts +71 -3
  114. package/src/routes/kit.ts +106 -3
  115. package/src/routes/prefs.ts +6 -6
  116. package/src/routes/recovery.ts +25 -42
  117. package/src/routes/request-trust.ts +97 -0
  118. package/src/routes/route-support.ts +208 -1
  119. package/src/routes/snapshots.ts +4 -9
  120. package/src/routes/sync.ts +4 -7
  121. package/src/security/redaction.ts +29 -23
  122. package/src/sync/backup-scheduler.ts +3 -6
  123. package/src/sync/sync-config.test.ts +24 -13
  124. package/src/ui/backup-inspect.ts +1 -1
  125. package/src/ui/dsh-profiles-view.ts +3 -5
  126. package/src/ui/i18n.test.ts +8 -3
  127. package/src/ui/snapshots-view.ts +2 -2
  128. package/src/utils/paths.test.ts +36 -1
  129. package/src/utils/paths.ts +30 -6
  130. package/src/utils/time.test.ts +46 -0
  131. package/src/utils/time.ts +55 -0
@@ -13,7 +13,7 @@ import type { TranslateNS } from '../client-types.ts'
13
13
  import type { SyncPushPreview } from '../../sync/sync-engine.ts'
14
14
  import type { UiT } from '../../ui/i18n.ts'
15
15
  import type { SectionId } from '../../schema/types.ts'
16
- import { Banner, Card } from '../common/ui.tsx'
16
+ import { Banner, Card, Chip } from '../common/ui.tsx'
17
17
  import { pushPreviewView } from './sync-view.ts'
18
18
  import css from '../config-manager.module.css'
19
19
 
@@ -44,7 +44,7 @@ export function PushPreviewCard({ preview, t, uiT, sectionName }: {
44
44
  <ul className={css.reportList}>
45
45
  {view.rows.map((row) => (
46
46
  <li key={row.section}>
47
- <span className={css.kindTag}>{row.changed ? t('syncflow.pushChanged') : t('syncflow.pushUnchanged')}</span>
47
+ <Chip>{row.changed ? t('syncflow.pushChanged') : t('syncflow.pushUnchanged')}</Chip>
48
48
  {' '}{sectionName(row.section)} · {row.count}
49
49
  </li>
50
50
  ))}
@@ -2,7 +2,7 @@
2
2
  * 一键同步差异确认视图(方案 A §5 差异确认数据流)。
3
3
  *
4
4
  * 消费 POST /sync/sync 返回的 items[],渲染逐项确认列表:
5
- * - 每项:kindTag + description + severity + 「采用远端」复选框(默认勾选,可取消);
5
+ * - 每项:Chip 适配器标签 + description + severity + 「采用远端」复选框(默认勾选,可取消);
6
6
  * - Conflict 项:内联弹窗(用本地 / 用远端 / 跳过);
7
7
  * - 底部:「确认导入」(apply-items)+「取消」(cancel)。
8
8
  *
@@ -228,7 +228,7 @@ export function SyncConfirmView(props: SyncConfirmViewProps): ReactNode {
228
228
 
229
229
  if (items.length === 0) {
230
230
  return (
231
- <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
231
+ <div className={css.blockStack}>
232
232
  <Banner kind="ok">{t('syncflow.empty')}</Banner>
233
233
  <div className={css.actionRow}>
234
234
  <Button disabled={busy} onClick={() => { void runCancel() }}>
@@ -240,7 +240,7 @@ export function SyncConfirmView(props: SyncConfirmViewProps): ReactNode {
240
240
  }
241
241
 
242
242
  return (
243
- <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
243
+ <div className={css.blockStack}>
244
244
  {/* 状态与计数一律徽章,不再先来一条整句 Banner:此前 Banner 与下面的徽章把「共 N 项差异」
245
245
  在同一屏里说了两遍。映射用 src/ui 的纯函数(等级 + 语义色),文案走 sync 字典 —— 不在这里另写分级规则。 */}
246
246
  <div className={css.statRow}>
@@ -343,7 +343,7 @@ export function SyncConfirmView(props: SyncConfirmViewProps): ReactNode {
343
343
  {(phase === 'done' || phase === 'failed') && applyResult !== null && (
344
344
  <>
345
345
  <ApplyResultCard result={applyResult} busy={busy} t={t} onRollback={runRollback} />
346
- <div className={css.actionRow} style={{ marginTop: '12px' }}>
346
+ <div className={css.actionRow + ' ' + css.actionRowSpaced}>
347
347
  <Button variant="primary" disabled={busy} onClick={() => { onCancel() }}>
348
348
  {t('common.close')}
349
349
  </Button>
@@ -377,7 +377,7 @@ export function SyncConfirmView(props: SyncConfirmViewProps): ReactNode {
377
377
  {/* R-04:回滚成功的 ok Banner 已改为 Toast(见 runRollback)。此处仅保留收尾「关闭」按钮;
378
378
  一并消除了原实现在 runApply 抛错(phase=failed 且 applyResult 仍为 null)时
379
379
  误显示「已回滚到应用前」的问题 —— 那种情况下方 error Banner 才是唯一事实。 */}
380
- <div className={css.actionRow} style={{ marginTop: '12px' }}>
380
+ <div className={css.actionRow + ' ' + css.actionRowSpaced}>
381
381
  <Button variant="primary" disabled={busy} onClick={() => { onCancel() }}>
382
382
  {t('common.close')}
383
383
  </Button>
@@ -123,7 +123,7 @@ function OperationRow({ row, t }: { row: SyncHistoryEntry; t: TranslateNS<'confi
123
123
  <tr>
124
124
  {/* 等宽 11px + 固定列宽 → 单行不换行;title 给完整本地时间(含秒) */}
125
125
  <td className={css.dim} title={formatDateTimeFull(row.createdAt)}>
126
- <span className={css.mono} style={{ fontSize: '11px' }}>{formatDateTime(row.createdAt)}</span>
126
+ <span className={css.mono + ' ' + css.syncLogTime}>{formatDateTime(row.createdAt)}</span>
127
127
  </td>
128
128
  <td>
129
129
  <div className={css.cellMain}>
@@ -149,7 +149,7 @@ function AutosyncRow({ entry, t }: { entry: AutosyncHistoryEntry; t: TranslateNS
149
149
  <tr>
150
150
  {/* 与人为操作行一致的时间呈现(等宽 11px 单行 + title 完整本地时间) */}
151
151
  <td className={css.dim} title={formatDateTimeFull(row.createdAt)}>
152
- <span className={css.mono} style={{ fontSize: '11px' }}>{formatDateTime(row.createdAt)}</span>
152
+ <span className={css.mono + ' ' + css.syncLogTime}>{formatDateTime(row.createdAt)}</span>
153
153
  </td>
154
154
  <td>
155
155
  <div className={css.cellMain}>
@@ -8,6 +8,7 @@
8
8
  import type { AutosyncHistoryEntry, SyncHistoryEntry } from './sync-api.ts'
9
9
  // 跳过原因码 → 字典键的映射键类型(**type-only**:不把 zh/en 目录按值带进本条 import)
10
10
  import type { SyncKey } from './sync-locales.ts'
11
+ import { formatMinuteStamp, parseDateInput } from '../../utils/time.ts'
11
12
  import type { TranslateNS } from '../client-types.ts'
12
13
 
13
14
  /** 同步命名空间翻译器(本文件的标签一律走它 —— 硬编码中文在英文界面下会原样透出)。 */
@@ -37,13 +38,11 @@ function byCreatedAtDesc(a: { createdAt: string }, b: { createdAt: string }): nu
37
38
  return a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0;
38
39
  }
39
40
 
40
- /** ISO 时间 → 本地可读字符串(短格式) */
41
+ /** ISO 时间 → 本地可读字符串(短格式);空串显示占位符、非法输入原样回显。 */
41
42
  export function formatDateTime(iso: string): string {
42
43
  if (!iso) return '—';
43
- const d = new Date(iso);
44
- if (isNaN(d.getTime())) return iso;
45
- const pad = (n: number) => String(n).padStart(2, '0');
46
- return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
44
+ const d = parseDateInput(iso);
45
+ return d === null ? iso : formatMinuteStamp(d);
47
46
  }
48
47
 
49
48
  /**
@@ -24,6 +24,7 @@ import { skipReasonKey } from './history-model.ts';
24
24
  import type { CloudConfigIssueCode } from '../../ui/sync-settings-view.ts';
25
25
  import type { S3CompatProvider } from '../../sync/sync-config.ts';
26
26
  import { currentUiLanguage, type UiT } from '../../ui/i18n.ts';
27
+ import { formatMinuteStamp, parseDateInput } from '../../utils/time.ts';
27
28
 
28
29
  /* ---------------------------------------------------------------- 私有仓库提示 */
29
30
 
@@ -565,10 +566,8 @@ export function computeSyncStatus(
565
566
 
566
567
  /** ISO-8601 → 本地可读时间(YYYY-MM-DD HH:mm;非法输入原样返回) */
567
568
  export function formatDateTime(iso: string): string {
568
- const d = new Date(iso);
569
- if (Number.isNaN(d.getTime())) return iso;
570
- const pad = (n: number): string => String(n).padStart(2, '0');
571
- return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
569
+ const d = parseDateInput(iso);
570
+ return d === null ? iso : formatMinuteStamp(d);
572
571
  }
573
572
 
574
573
  /** 上次同步时间的展示文本('' / undefined = 从未同步) */
@@ -0,0 +1,37 @@
1
+ /**
2
+ * 围栏拒绝码(access-mode)—— 宿主路由与浏览器两半的**唯一字面量来源**。
3
+ *
4
+ * 为什么需要独立模块:issue #126 里局域网访问内嵌面板时,每条只读路由都回
5
+ * `{"error":"forbidden: loopback-only"}`,而界面只能把它当普通错误显示成
6
+ * 「有 5 项数据读取失败」+ 一个点了没用的「重试」—— 用户据此会以为数据坏了。
7
+ * 客户端要能认出「这是访问方式问题、不是数据问题」,就必须有一个**机器码**,
8
+ * 且这个码不能各写一份(宿主 kit 写一个、浏览器 api 写一个,早晚分叉)。
9
+ *
10
+ * 三档语义(与 src/routes/kit.ts 的围栏一一对应):
11
+ * - `loopback-only`:只接受本机回环(无宿主信任面可委托时的兜底 / 独立 CLI 救急台);
12
+ * - `untrusted-authority`:宿主拒绝了这次请求的 Host/Origin(不在 trustedHosts);
13
+ * - `browser-session`:地址可信但缺 dsh web 的登录会话 cookie(401)。
14
+ *
15
+ * 本模块零依赖、零 import(宿主与浏览器 bundle 都要能引)。
16
+ */
17
+
18
+ /** 只接受回环(无委托或委托不可用)。 */
19
+ export const LOOPBACK_ONLY_CODE = 'loopback-only' as const
20
+
21
+ /** 宿主不认这个 authority(Host 头不在 trustedHosts)。 */
22
+ export const UNTRUSTED_AUTHORITY_CODE = 'untrusted-authority' as const
23
+
24
+ /** 地址可信,但请求没有有效的 dsh web 登录会话。 */
25
+ export const BROWSER_SESSION_CODE = 'browser-session' as const
26
+
27
+ export type AccessModeCode =
28
+ | typeof LOOPBACK_ONLY_CODE
29
+ | typeof UNTRUSTED_AUTHORITY_CODE
30
+ | typeof BROWSER_SESSION_CODE
31
+
32
+ const ACCESS_MODE_CODES: readonly string[] = [LOOPBACK_ONLY_CODE, UNTRUSTED_AUTHORITY_CODE, BROWSER_SESSION_CODE]
33
+
34
+ /** 该 code 是否属于「访问方式」这一类拒绝(客户端据此换文案,而不是当成读取失败)。 */
35
+ export function isAccessModeCode(value: unknown): value is AccessModeCode {
36
+ return typeof value === 'string' && ACCESS_MODE_CODES.includes(value)
37
+ }
@@ -17,6 +17,7 @@ import { buildManifest, CHECKSUMS_FILE, MANIFEST_FILE, EXPORTER_NAME } from '../
17
17
  import { SECTION_JSON_PATHS, SECTION_FILE_PREFIXES, isFileSection } from '../schema/config.ts';
18
18
  import { DEFAULT_SENSITIVE_RELS, refreshVault } from '../security/vault.ts';
19
19
  import { writeZip } from '../utils/zip.ts';
20
+ import { formatDateOnly } from '../utils/time.ts';
20
21
  import { msgOf } from './messages.ts';
21
22
  import { engineMsg } from './messages-core.ts';
22
23
  import { declareBundledSessionsInWorkspaces, normalizeSessionLimit, sessionIdKey } from './session-select.ts';
@@ -533,10 +534,7 @@ function buildSectionFlags(sections: ExportSection[]): Manifest['sections'] {
533
534
  }
534
535
 
535
536
  function defaultOutPath(now: Date): string {
536
- const y = now.getFullYear();
537
- const m = String(now.getMonth() + 1).padStart(2, '0');
538
- const d = String(now.getDate()).padStart(2, '0');
539
- return `dsh-config-${y}-${m}-${d}.zip`;
537
+ return `dsh-config-${formatDateOnly(now)}.zip`;
540
538
  }
541
539
 
542
540
  /** 供报告使用:导出器身份(避免与 manifest 常量重复维护) */
@@ -0,0 +1,84 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { createCacheCleanupScheduler } from './cache-cleanup.ts';
4
+
5
+ /** 收集日志的假 log 口(只记 info/warn 文本,便于断言「失败不静默」)。 */
6
+ function fakeLog(): { info: string[]; warn: string[]; sink: { info(m: string): void; warn(m: string): void } } {
7
+ const info: string[] = [];
8
+ const warn: string[] = [];
9
+ return { info, warn, sink: { info: (m) => { info.push(m); }, warn: (m) => { warn.push(m); } } };
10
+ }
11
+
12
+ const tick = async (ms = 30): Promise<void> => { await new Promise((resolve) => { setTimeout(resolve, ms); }); };
13
+
14
+ test('CC-1 start 立即清一次,并按周期继续清', async () => {
15
+ let calls = 0;
16
+ const { sink } = fakeLog();
17
+ const scheduler = createCacheCleanupScheduler({ cleanup: async () => { calls += 1; return { removed: 0, freedBytes: 0 }; }, intervalMs: 10, log: sink });
18
+ scheduler.start();
19
+ assert.equal(calls, 1);
20
+ await tick(45);
21
+ assert.ok(calls >= 3, `期望至少 3 次(1 次启动 + 定时),实际 ${calls}`);
22
+ scheduler.dispose();
23
+ });
24
+
25
+ test('CC-2 start 幂等:重复调用不叠定时器', async () => {
26
+ let calls = 0;
27
+ const { sink } = fakeLog();
28
+ const scheduler = createCacheCleanupScheduler({ cleanup: async () => { calls += 1; return { removed: 0, freedBytes: 0 }; }, intervalMs: 10, log: sink });
29
+ scheduler.start();
30
+ scheduler.start();
31
+ assert.equal(calls, 1, '第二次 start 不得再同步清一次');
32
+ await tick(35);
33
+ // 单个定时器:10ms 周期下 35ms 内不会超过 1 + 4 次
34
+ assert.ok(calls <= 5, `定时器疑似叠了:${calls}`);
35
+ scheduler.dispose();
36
+ });
37
+
38
+ test('CC-3 dispose 停掉定时器且幂等', async () => {
39
+ let calls = 0;
40
+ const { sink } = fakeLog();
41
+ const scheduler = createCacheCleanupScheduler({ cleanup: async () => { calls += 1; return { removed: 0, freedBytes: 0 }; }, intervalMs: 10, log: sink });
42
+ scheduler.start();
43
+ scheduler.dispose();
44
+ scheduler.dispose();
45
+ const afterDispose = calls;
46
+ await tick(35);
47
+ assert.equal(calls, afterDispose, 'dispose 之后不得再有清理');
48
+ });
49
+
50
+ test('CC-4 removed > 0 才记 info(0 个不刷噪音)', async () => {
51
+ const { info, sink } = fakeLog();
52
+ const zero = createCacheCleanupScheduler({ cleanup: async () => ({ removed: 0, freedBytes: 0 }), intervalMs: 1000, log: sink });
53
+ zero.runNow();
54
+ await tick(10);
55
+ assert.deepEqual(info, []);
56
+ const one = createCacheCleanupScheduler({ cleanup: async () => ({ removed: 2, freedBytes: 128 }), intervalMs: 1000, log: sink });
57
+ one.runNow();
58
+ await tick(10);
59
+ assert.equal(info.length, 1);
60
+ });
61
+
62
+ test('CC-5 清理失败只记 warn(含错误文本),不抛、不停表', async () => {
63
+ const { warn, sink } = fakeLog();
64
+ let calls = 0;
65
+ const scheduler = createCacheCleanupScheduler({
66
+ cleanup: async () => { calls += 1; throw new Error('disk on fire'); },
67
+ intervalMs: 10,
68
+ log: sink,
69
+ });
70
+ scheduler.start();
71
+ await tick(35);
72
+ assert.ok(calls >= 2, '失败后定时器必须继续跑');
73
+ assert.ok(warn.length >= 1);
74
+ assert.match(warn[0] ?? '', /缓存自动清理失败/);
75
+ scheduler.dispose();
76
+ });
77
+
78
+ test('CC-6 非 Error 抛出也如实成字符串(不吞形状)', async () => {
79
+ const { warn, sink } = fakeLog();
80
+ const scheduler = createCacheCleanupScheduler({ cleanup: () => Promise.reject('boom'), intervalMs: 1000, log: sink });
81
+ scheduler.runNow();
82
+ await tick(10);
83
+ assert.equal(warn.length, 1);
84
+ });
@@ -0,0 +1,74 @@
1
+ /**
2
+ * 宿主缓存自动清理的**调度**部分(tech-debt #23 下沉:index.ts 只留一次装配)。
3
+ *
4
+ * 为什么单独成模块:清理动作本身在 `core/cache-cleaner.ts`(纯 IO + 保留期判定,已单测),
5
+ * 而「什么时候跑、跑几次、跑挂了怎么办」是**调度语义**,此前和 apply() 的其他接线混在
6
+ * src/index.ts 里,无法在不挂宿主的情况下验证。这里把调度抽成**可注入动作**的薄壳:
7
+ *
8
+ * - 启动即清一次 + 按 `intervalMs` 定时清(默认由调用方给 24h);
9
+ * - 每一次清理都是**尽力而为**:失败只记 warn,绝不打断插件挂载、也不停掉定时器
10
+ * (定时器停掉的代价是「以后再也不清」,比一次失败严重得多);
11
+ * - `removed === 0` 不记 info(每次启动都刷一行「清理完成 0 个」是噪音)。
12
+ *
13
+ * 边界:本文件只依赖 `node:` 与本地相对导入(core 子目录不得 import core 兄弟模块,
14
+ * 见 tests/architecture-boundaries.test.ts 的 allow 白名单),因此清理动作与日志口一律注入。
15
+ */
16
+
17
+ /** 一次清理的可观测结果(`core/cache-cleaner.ts` 的 CacheCleanupResult 满足此形状)。 */
18
+ export interface CacheCleanupTally {
19
+ removed: number
20
+ freedBytes: number
21
+ }
22
+
23
+ /** 日志口:只用到 info / warn,宿主 host.log 直接满足。 */
24
+ export interface CacheCleanupLogSink {
25
+ info(message: string, meta?: Record<string, unknown>): void
26
+ warn(message: string, meta?: Record<string, unknown>): void
27
+ }
28
+
29
+ export interface CacheCleanupSchedulerOptions {
30
+ /** 执行一次清理(注入 `cleanupCaches` 的绑定版本,便于单测替换)。 */
31
+ cleanup: () => Promise<CacheCleanupTally>
32
+ /** 定时周期(毫秒)。 */
33
+ intervalMs: number
34
+ log: CacheCleanupLogSink
35
+ }
36
+
37
+ export interface CacheCleanupScheduler {
38
+ /** 启动:立即清一次 + 挂上定时器(重复调用幂等,不会叠出第二个定时器)。 */
39
+ start(): void
40
+ /** 停掉定时器(插件卸载 / 宿主关停)。幂等。 */
41
+ dispose(): void
42
+ /** 立刻清一次(启动路径与手动触发共用同一条错误口径)。 */
43
+ runNow(): void
44
+ }
45
+
46
+ export function createCacheCleanupScheduler(options: CacheCleanupSchedulerOptions): CacheCleanupScheduler {
47
+ let timer: ReturnType<typeof setInterval> | null = null
48
+
49
+ const runNow = (): void => {
50
+ void options.cleanup()
51
+ .then((report) => {
52
+ if (report.removed > 0) {
53
+ options.log.info('缓存自动清理完成', { removed: report.removed, freedBytes: report.freedBytes })
54
+ }
55
+ })
56
+ .catch((error: unknown) => {
57
+ options.log.warn('缓存自动清理失败', { error: error instanceof Error ? error.message : String(error) })
58
+ })
59
+ }
60
+
61
+ return {
62
+ runNow,
63
+ start(): void {
64
+ if (timer !== null) return
65
+ runNow()
66
+ timer = setInterval(runNow, options.intervalMs)
67
+ },
68
+ dispose(): void {
69
+ if (timer === null) return
70
+ clearInterval(timer)
71
+ timer = null
72
+ },
73
+ }
74
+ }
@@ -0,0 +1,111 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { createHostLifecycle } from './lifecycle-hooks.ts';
4
+
5
+ interface Recorder {
6
+ calls: string[]
7
+ effects: Array<{ label: string; dispose: () => void }>
8
+ }
9
+
10
+ function harness(overrides: Partial<{ releaseLockThrows: boolean }> = {}): {
11
+ rec: Recorder
12
+ lifecycle: ReturnType<typeof createHostLifecycle>
13
+ /** 注入的退出释放函数(判定 'exit' 监听有无用它做身份比对,别用进程级计数)。 */
14
+ release: () => void
15
+ /** 卸载全部已注册的 effect(测试收尾:别把 exit 监听留给下一个用例)。 */
16
+ disposeAll: () => void
17
+ } {
18
+ const rec: Recorder = { calls: [], effects: [] };
19
+ const release = (): void => {
20
+ if (overrides.releaseLockThrows === true) throw new Error('release failed');
21
+ rec.calls.push('lock.release');
22
+ };
23
+ const lifecycle = createHostLifecycle({
24
+ scheduler: { start: () => { rec.calls.push('autosync.start'); }, stop: () => { rec.calls.push('autosync.stop'); } },
25
+ backupScheduler: { start: () => { rec.calls.push('backup.start'); }, stop: () => { rec.calls.push('backup.stop'); } },
26
+ releaseLockOnExit: release,
27
+ profileRuntime: {
28
+ startHeartbeat: () => { rec.calls.push('heartbeat.start'); return () => { rec.calls.push('heartbeat.stop'); }; },
29
+ withdraw: () => { rec.calls.push('heartbeat.withdraw'); },
30
+ },
31
+ effect: (label, setup) => { rec.effects.push({ label, dispose: setup() }); },
32
+ });
33
+ return { rec, lifecycle, release, disposeAll: () => { for (const e of rec.effects) e.dispose(); } };
34
+ }
35
+
36
+ test('HL-1 分类 NORMAL 且已 arm → 两个调度器都启动,顺序固定', () => {
37
+ const { rec, lifecycle } = harness();
38
+ lifecycle.arm();
39
+ lifecycle.onStartupClassified('NORMAL');
40
+ assert.deepEqual(rec.calls, ['autosync.start', 'backup.start']);
41
+ assert.equal(lifecycle.started(), true);
42
+ });
43
+
44
+ test('HL-2 先分类后 arm(apply 同步晚一步的竞态)→ 同样启动', () => {
45
+ const { rec, lifecycle } = harness();
46
+ lifecycle.onStartupClassified('NORMAL');
47
+ assert.deepEqual(rec.calls, []);
48
+ lifecycle.arm();
49
+ assert.deepEqual(rec.calls, ['autosync.start', 'backup.start']);
50
+ });
51
+
52
+ test('HL-3 结论 BLOCKED → 永不启动;后续再给 NORMAL 也不启动(分类结论只有一次)', () => {
53
+ const { rec, lifecycle } = harness();
54
+ lifecycle.arm();
55
+ lifecycle.onStartupClassified('BLOCKED');
56
+ lifecycle.onStartupClassified('NORMAL');
57
+ assert.deepEqual(rec.calls, []);
58
+ assert.equal(lifecycle.started(), false);
59
+ });
60
+
61
+ test('HL-4 只启动一次:arm 与分类重复调用都不重复 start', () => {
62
+ const { rec, lifecycle } = harness();
63
+ lifecycle.arm();
64
+ lifecycle.arm();
65
+ lifecycle.onStartupClassified('NORMAL');
66
+ lifecycle.onStartupClassified('NORMAL');
67
+ lifecycle.arm();
68
+ assert.deepEqual(rec.calls, ['autosync.start', 'backup.start']);
69
+ });
70
+
71
+ test('HL-5 mount 注册四条卸载清理;重复 mount 不重复注册', () => {
72
+ const { rec, lifecycle, disposeAll } = harness();
73
+ lifecycle.mount();
74
+ lifecycle.mount();
75
+ assert.deepEqual(rec.effects.map((e) => e.label), [
76
+ 'config-manager: backup scheduler',
77
+ 'config-manager: autosync scheduler',
78
+ 'config-manager: environment lock exit release',
79
+ 'config-manager: profile runtime heartbeat',
80
+ ]);
81
+ disposeAll();
82
+ });
83
+
84
+ test('HL-6 卸载:先停调度器,再摘 exit 监听并释放锁,最后撤回心跳', () => {
85
+ const { rec, lifecycle, release, disposeAll } = harness();
86
+ lifecycle.mount();
87
+ assert.ok(process.listeners('exit').includes(release), 'mount 后必须有退出监听');
88
+ // ctx.effect 语义:setup 立即执行(心跳此刻起报),dispose 时才跑返回的清理
89
+ assert.deepEqual(rec.calls, ['heartbeat.start']);
90
+ disposeAll();
91
+ assert.deepEqual(rec.calls, [
92
+ 'heartbeat.start',
93
+ 'backup.stop',
94
+ 'autosync.stop',
95
+ 'lock.release',
96
+ 'heartbeat.stop',
97
+ 'heartbeat.withdraw',
98
+ ]);
99
+ assert.equal(process.listeners('exit').includes(release), false, 'exit 监听必须被移除(不留孤儿)');
100
+ });
101
+
102
+ test('HL-7 释放抛错不影响卸载链的其余步骤', () => {
103
+ const { rec, lifecycle, release } = harness({ releaseLockThrows: true });
104
+ lifecycle.mount();
105
+ const exitEffect = rec.effects[2];
106
+ assert.ok(exitEffect !== undefined);
107
+ assert.throws(() => { exitEffect.dispose(); }, /release failed/);
108
+ assert.equal(process.listeners('exit').includes(release), false, '抛错前必须先摘监听');
109
+ // 收尾:心跳 effect 还在,手动卸掉
110
+ for (const e of rec.effects) { if (e !== exitEffect) e.dispose(); }
111
+ });
@@ -0,0 +1,118 @@
1
+ /**
2
+ * 宿主生命周期的**调度接线**(tech-debt #23 下沉):调度器启停、退出兜底释放环境锁、
3
+ * 实例心跳。此前这些散在 src/index.ts 的 apply() 里,只能靠「装上宿主跑一遍」验证。
4
+ *
5
+ * 两条语义在这里被钉住(它们都是踩过的坑):
6
+ *
7
+ * 1. **调度器只在启动分类为 NORMAL 后才启动**(P1-B)。分类是异步的、apply() 是同步的,
8
+ * 两边谁先到都可能 —— 于是用「arm(接线就绪)+ classify(结论到达)」两个状态位收敛,
9
+ * 任一顺序都能得出正确结果,且 `started` 保证只启动一次。
10
+ * 2. **退出时必须兜底释放环境锁**。关窗时后台同步的 finally 等不到 ⇒ 锁留盘,
11
+ * 下次启动整轮被判 STALE(见 core/env-lock-lifecycle.ts)。释放函数本身是幂等的。
12
+ *
13
+ * 边界:本文件只依赖 `node:`(core 子目录不得 import core 兄弟模块),
14
+ * 因此调度器、心跳器、effect 注册口一律注入。
15
+ */
16
+
17
+ /** 可启停的宿主调度器(AutoSyncScheduler / BackupScheduler 都满足)。 */
18
+ export interface StartStoppable {
19
+ start(): void
20
+ stop(): void
21
+ }
22
+
23
+ /** 实例心跳(DshProfileRuntimeRegistry 满足):返回停止函数。 */
24
+ export interface HeartbeatRuntime {
25
+ startHeartbeat(): () => void
26
+ withdraw(): void
27
+ }
28
+
29
+ /** 卸载清理的注册口(宿主 Cordis 的 ctx.effect 注入薄壳)。 */
30
+ export type EffectRegistrar = (label: string, setup: () => () => void) => void
31
+
32
+ export interface HostLifecycleOptions {
33
+ scheduler: StartStoppable
34
+ backupScheduler: StartStoppable
35
+ /**
36
+ * 退出兜底释放环境锁(`createExitLockReleaser(envLockManager)` 的绑定)。
37
+ * 幂等:正常卸载时 effect 会再调一次。
38
+ */
39
+ releaseLockOnExit: () => void
40
+ profileRuntime: HeartbeatRuntime
41
+ effect: EffectRegistrar
42
+ }
43
+
44
+ /** 启动分类结论:只有 NORMAL 放行调度器。 */
45
+ export type StartupVerdict = 'NORMAL' | 'BLOCKED'
46
+
47
+ export interface HostLifecycle {
48
+ /** 注册全部卸载清理(幂等:重复调用不重复注册)。 */
49
+ mount(): void
50
+ /** 接线就绪(scheduler / backupScheduler 已构造完成),可接受启动。 */
51
+ arm(): void
52
+ /** 启动分类结论到达;NORMAL 且已 arm 时立即启动调度器。BLOCKED 为终态,不可翻案。 */
53
+ onStartupClassified(verdict: StartupVerdict): void
54
+ /** 调度器是否真的启动过(只读,供诊断/测试) */
55
+ started(): boolean
56
+ }
57
+
58
+ export function createHostLifecycle(options: HostLifecycleOptions): HostLifecycle {
59
+ let mounted = false
60
+ let armed = false
61
+ let blocked = false
62
+ let shouldStart = false
63
+ let started = false
64
+
65
+ const tryStart = (): void => {
66
+ if (!armed || !shouldStart || started) return
67
+ // 先置位再调用:某个 start 抛错时也不会在下一轮重复启动(避免定时器叠两份)。
68
+ started = true
69
+ options.scheduler.start()
70
+ options.backupScheduler.start()
71
+ }
72
+
73
+ return {
74
+ mount(): void {
75
+ if (mounted) return
76
+ mounted = true
77
+ // 自动同步调度器随插件生命周期停止:重载/卸载时清理定时器,
78
+ // 避免旧调度器残留导致重复后台同步。
79
+ options.effect('config-manager: backup scheduler', () => () => options.backupScheduler.stop())
80
+ options.effect('config-manager: autosync scheduler', () => () => options.scheduler.stop())
81
+ // 退出兜底:关窗时若后台同步正在跑,各入口的 finally 等不到 ⇒ 锁留盘。
82
+ // 强杀 / 崩溃 / 断电仍靠下次启动的自动回收兜底。
83
+ process.once('exit', options.releaseLockOnExit)
84
+ options.effect('config-manager: environment lock exit release', () => () => {
85
+ process.removeListener('exit', options.releaseLockOnExit)
86
+ options.releaseLockOnExit()
87
+ })
88
+ // m-profiles:实例心跳(自报 + 定期刷新);卸载时撤回自己的心跳文件,
89
+ // 别让别人把死实例当成活的。
90
+ options.effect('config-manager: profile runtime heartbeat', () => {
91
+ const stopHeartbeat = options.profileRuntime.startHeartbeat()
92
+ return () => {
93
+ stopHeartbeat()
94
+ options.profileRuntime.withdraw()
95
+ }
96
+ })
97
+ },
98
+ arm(): void {
99
+ armed = true
100
+ tryStart()
101
+ },
102
+ onStartupClassified(verdict: StartupVerdict): void {
103
+ // BLOCKED 是终态:分类结论只到一次,后续再来 NORMAL 只可能是接线出错,
104
+ // 此时放行后台定时器等于绕过 SAFE MODE 判定 ⇒ fail-closed。
105
+ if (blocked) return
106
+ if (verdict === 'BLOCKED') {
107
+ blocked = true
108
+ shouldStart = false
109
+ return
110
+ }
111
+ shouldStart = true
112
+ tryStart()
113
+ },
114
+ started(): boolean {
115
+ return started
116
+ },
117
+ }
118
+ }