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
@@ -0,0 +1,45 @@
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
+ /** 交给 `resolveStartupSafeMode` 的锁状态口径(与 `mapLockStateForStartup` 同一来源,不另立枚举)。 */
20
+ export type StartupLockState = ReturnType<typeof mapLockStateForStartup>;
21
+ /** 只要求 info/warn(宿主 logger 结构兼容;测试用假 logger 即可)。 */
22
+ export interface LockLifecycleLog {
23
+ info(message: string): void;
24
+ warn(message: string): void;
25
+ }
26
+ /** 自愈只碰这三个动作,不把整个 manager 传进来(也就无法顺手 acquire/validate)。 */
27
+ type LockLifecyclePort = Pick<EnvironmentLockManager, 'reclaimProvableStaleLock' | 'cleanupOrphanHeartbeats' | 'releaseOnExitSync'>;
28
+ /**
29
+ * 启动自愈:回收可证 stale 残留锁 + 清孤儿心跳,返回应当交给 SAFE MODE 判定的锁状态。
30
+ *
31
+ * 回收成功后返回 `'FREE'`:否则「无活锁者」的陈旧标记不会被一并复位,本会话的写操作会继续被 423 挡着
32
+ * (界面却说没有待处理事项)。回收被拒(证明不出已死)时原样返回,只记一条 warn。
33
+ */
34
+ export declare function reclaimStaleLockAtStartup(input: {
35
+ kind: string;
36
+ inspected: LockState;
37
+ lock: LockLifecyclePort;
38
+ log: LockLifecycleLog;
39
+ }): Promise<StartupLockState>;
40
+ /**
41
+ * 生成退出释放钩子:只删**本实例 instanceId** 的 ownership 与心跳(与 `release()` 同一不变量),永不抛。
42
+ * 调用方负责 `process.once('exit', fn)` 与 dispose 时摘钩。
43
+ */
44
+ export declare function createExitLockReleaser(lock: Pick<EnvironmentLockManager, 'releaseOnExitSync'>): () => void;
45
+ export {};
@@ -0,0 +1,43 @@
1
+ import { mapLockStateForStartup } from './phase3-host.js';
2
+ import { utilsMsg } from '../utils/messages-utils.js';
3
+ /**
4
+ * 启动自愈:回收可证 stale 残留锁 + 清孤儿心跳,返回应当交给 SAFE MODE 判定的锁状态。
5
+ *
6
+ * 回收成功后返回 `'FREE'`:否则「无活锁者」的陈旧标记不会被一并复位,本会话的写操作会继续被 423 挡着
7
+ * (界面却说没有待处理事项)。回收被拒(证明不出已死)时原样返回,只记一条 warn。
8
+ */
9
+ export async function reclaimStaleLockAtStartup(input) {
10
+ let lockState = mapLockStateForStartup(input.inspected);
11
+ if (input.kind === 'NORMAL' && input.inspected === 'STALE_LOCK_DETECTED') {
12
+ const reclaimed = await input.lock.reclaimProvableStaleLock().catch(() => null);
13
+ if (reclaimed !== null && reclaimed.ok) {
14
+ lockState = 'FREE';
15
+ input.log.info(utilsMsg('utils.envLock.autoReclaimedStale', {
16
+ op: reclaimed.removedOwner?.op ?? 'unknown',
17
+ pid: reclaimed.removedOwner?.pid ?? 0,
18
+ }));
19
+ }
20
+ else if (reclaimed !== null) {
21
+ input.log.warn(`残留锁自动回收被拒(保留现场,走显式回收):${reclaimed.detail ?? ''}`);
22
+ }
23
+ }
24
+ if (input.kind === 'NORMAL') {
25
+ const orphaned = await input.lock.cleanupOrphanHeartbeats().catch(() => 0);
26
+ if (orphaned > 0)
27
+ input.log.info(utilsMsg('utils.envLock.orphanHeartbeatsRemoved', { count: orphaned }));
28
+ }
29
+ return lockState;
30
+ }
31
+ /**
32
+ * 生成退出释放钩子:只删**本实例 instanceId** 的 ownership 与心跳(与 `release()` 同一不变量),永不抛。
33
+ * 调用方负责 `process.once('exit', fn)` 与 dispose 时摘钩。
34
+ */
35
+ export function createExitLockReleaser(lock) {
36
+ return () => {
37
+ try {
38
+ lock.releaseOnExitSync();
39
+ }
40
+ catch { /* 退出路径不许抛 */ }
41
+ };
42
+ }
43
+ //# sourceMappingURL=env-lock-lifecycle.js.map
@@ -0,0 +1,34 @@
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 { type MigrationStore } from './migration-history.ts';
13
+ /** 只用到 retention;收窄依赖便于单测替身。 */
14
+ export type HistoryPruneStore = Pick<MigrationStore, 'retention'>;
15
+ export interface HistoryPruneLogger {
16
+ info(message: string, meta?: Record<string, unknown>): void;
17
+ warn(message: string, meta?: Record<string, unknown>): void;
18
+ }
19
+ export interface HistoryPrunerOptions {
20
+ history: HistoryPruneStore;
21
+ /**
22
+ * 读取用户配置的保留上限(原值,非法由 resolveHistoryRetention 归一)。
23
+ * 由宿主注入:core 层不得 import ../sync/*(tests/architecture-boundaries.test.ts)。
24
+ */
25
+ readRetentionLimit: () => Promise<unknown>;
26
+ log: HistoryPruneLogger;
27
+ /** 写入触发的节流窗口(缺省 60 s);启动触发不受它影响。 */
28
+ intervalMs?: number;
29
+ /** 注入时钟(测试用)。 */
30
+ now?: () => number;
31
+ }
32
+ export type HistoryPruneTrigger = 'startup' | 'append';
33
+ /** 返回 pruneHistory(trigger):fire-and-forget 调用,永不抛错(失败只进日志)。 */
34
+ export declare function createHistoryPruner(options: HistoryPrunerOptions): (trigger: HistoryPruneTrigger) => Promise<void>;
@@ -0,0 +1,43 @@
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 } from './migration-history.js';
13
+ /** 返回 pruneHistory(trigger):fire-and-forget 调用,永不抛错(失败只进日志)。 */
14
+ export function createHistoryPruner(options) {
15
+ const { history, readRetentionLimit, log, intervalMs = 60_000, now = Date.now } = options;
16
+ let inFlight = false;
17
+ let lastAt = 0;
18
+ return async function pruneHistory(trigger) {
19
+ if (inFlight)
20
+ return;
21
+ const at = now();
22
+ // 节流只压「写入触发」:lastAt 由上一次实际执行决定,启动那一次基本总是放行。
23
+ if (trigger === 'append' && at - lastAt < intervalMs)
24
+ return;
25
+ inFlight = true;
26
+ lastAt = at;
27
+ try {
28
+ const limit = resolveHistoryRetention(await readRetentionLimit());
29
+ if (limit <= 0)
30
+ return;
31
+ const removed = await history.retention(limit);
32
+ if (removed.length > 0)
33
+ log.info('迁移历史自动清理', { maxEntries: limit, removed: removed.length });
34
+ }
35
+ catch (error) {
36
+ log.warn('迁移历史自动清理失败', { error: error instanceof Error ? error.message : String(error) });
37
+ }
38
+ finally {
39
+ inFlight = false;
40
+ }
41
+ };
42
+ }
43
+ //# sourceMappingURL=history-prune.js.map
@@ -13,5 +13,5 @@ export { ImportNotConfirmedError, ImportFailedError, } from './types.ts';
13
13
  export type * from './types.ts';
14
14
  export { applyPathMapping, type PathMappingRule } from './path-mapping.ts';
15
15
  export { planSessionRepair, sessionRepairNeedsAttention, type SessionRepairAction, type SessionRepairActionKind, type SessionRepairOptions, type SessionRepairPlan, type SessionRepairReason, type SessionRepairSummary, type RepairSessionInput, } from './session-repair.ts';
16
- export { MigrationStore, sanitizeEntry, queryHistory, summarizeHistory, renderExport, parseHistoryQuery, isValidMigrationKind, redactHistoryText, makeHistoryFilename, isHistoryBasename, MIGRATION_HISTORY_DIR, DEFAULT_MIGRATION_RETENTION, MIGRATION_HISTORY_SCHEMA_VERSION, type MigrationKind, type MigrationResult, type MigrationHistoryEntry, type StoredMigrationHistoryEntry, type MigrationQuery, type MigrationHistoryStats, type ExportFormat, type ReadMigrationResult, type AppendResult, type MigrationIo, type MigrationStoreOptions, type MigrationSource, } from './migration-history.ts';
16
+ export { MigrationStore, sanitizeEntry, queryHistory, summarizeHistory, renderExport, parseHistoryQuery, isValidMigrationKind, redactHistoryText, makeHistoryFilename, isHistoryBasename, MIGRATION_HISTORY_DIR, DEFAULT_MIGRATION_RETENTION, MIGRATION_HISTORY_SCHEMA_VERSION, HISTORY_RETENTION_MIN, HISTORY_RETENTION_MAX, isValidHistoryRetention, resolveHistoryRetention, type MigrationKind, type MigrationResult, type MigrationHistoryEntry, type StoredMigrationHistoryEntry, type MigrationQuery, type MigrationHistoryStats, type ExportFormat, type ReadMigrationResult, type AppendResult, type MigrationIo, type MigrationStoreOptions, type MigrationSource, } from './migration-history.ts';
17
17
  export type { ExportOptions, ExportSection, ValidationResult, HostContext, SettingsFacade, CredentialsFacade, PluginsFacade, WorkspaceFacade, PatchFileFacade, FileSystemFacade, NamespaceInfo, PluginInfo, ConfigAdapter, Portability, SecretScanner, SensitiveHit, EncryptionProvider, PlanItem, PlanItemKind, ItemResolution, GlobalConflictStrategy, ImportAnalysis, ImportDecisions, ImportPlan, ImportResult, ExecutedItem, ImportContext, SnapshotTarget, SnapshotEntry, Snapshot, SnapshotStore, RollbackReport, PathMapping, PathIssue, CompatibilityInput, CompatibilityScore, ExportReport, ApplyResult, ConflictDecision, } from './types.ts';
package/lib/core/index.js CHANGED
@@ -15,5 +15,5 @@ export { ImportNotConfirmedError, ImportFailedError, } from './types.js';
15
15
  export { applyPathMapping } from './path-mapping.js';
16
16
  export { planSessionRepair, sessionRepairNeedsAttention, } from './session-repair.js';
17
17
  /* —— 迁移历史引擎(Phase 6) —— */
18
- export { MigrationStore, sanitizeEntry, queryHistory, summarizeHistory, renderExport, parseHistoryQuery, isValidMigrationKind, redactHistoryText, makeHistoryFilename, isHistoryBasename, MIGRATION_HISTORY_DIR, DEFAULT_MIGRATION_RETENTION, MIGRATION_HISTORY_SCHEMA_VERSION, } from './migration-history.js';
18
+ export { MigrationStore, sanitizeEntry, queryHistory, summarizeHistory, renderExport, parseHistoryQuery, isValidMigrationKind, redactHistoryText, makeHistoryFilename, isHistoryBasename, MIGRATION_HISTORY_DIR, DEFAULT_MIGRATION_RETENTION, MIGRATION_HISTORY_SCHEMA_VERSION, HISTORY_RETENTION_MIN, HISTORY_RETENTION_MAX, isValidHistoryRetention, resolveHistoryRetention, } from './migration-history.js';
19
19
  //# sourceMappingURL=index.js.map
@@ -2,6 +2,19 @@ export declare const MIGRATION_HISTORY_SCHEMA_VERSION = 1;
2
2
  export declare const MIGRATION_HISTORY_DIR = "migration-history";
3
3
  /** 默认保留上限(retention 删最旧)。 */
4
4
  export declare const DEFAULT_MIGRATION_RETENTION = 1000;
5
+ /** 用户可配置的保留上限区间(0 = 不限制;上限防「一次填 10 亿」把 UI 输入当系统限制用)。 */
6
+ export declare const HISTORY_RETENTION_MIN = 0;
7
+ export declare const HISTORY_RETENTION_MAX = 100000;
8
+ /**
9
+ * 保留上限字面量校验(路由/偏好共用的唯一口径):只接受区间内的整数。
10
+ * 非法(字符串 / 小数 / 负数 / 越界)一律 false —— 调用方不得自行 Math.trunc 后放行。
11
+ */
12
+ export declare function isValidHistoryRetention(value: unknown): value is number;
13
+ /**
14
+ * 有效保留上限:用户配置值合法则用它,否则回落默认(1000)。
15
+ * 0 = 不限制(由 retention 自己短路),缺省/损坏 → 默认档。
16
+ */
17
+ export declare function resolveHistoryRetention(configured: unknown): number;
5
18
  /** 合法 kind 集合(§5 COMPLETE 清单 + 评审补 'profile-import')。 */
6
19
  declare const MIGRATION_KINDS: readonly ['import', 'restore', 'rollback', 'profile-create', 'profile-select', 'profile-switch', 'profile-delete', 'profile-rename', 'profile-save', 'profile-import', 'sync-apply', 'autosync', 'recovery', 'backup', 'backup-manual', 'snapshot-delete', 'snapshot-prune'];
7
20
  /** §5 覆盖的操作 kind(COMPLETE 不变量;常量枚举,天然非敏感)。 */
@@ -63,6 +76,8 @@ export interface ReadMigrationResult {
63
76
  entries: StoredMigrationHistoryEntry[];
64
77
  /** 被跳过/损坏的文件名(读取时识别,UI 可选警示;不静默接受)。 */
65
78
  corrupted: string[];
79
+ /** 目录内**合法历史文件**总数(含被 limit 窗口挡在外的旧条目;未统计时为 undefined)。 */
80
+ total?: number;
66
81
  }
67
82
  /** 追加写入结果(best-effort 调用方据此判断降级)。 */
68
83
  export interface AppendResult {
@@ -134,8 +149,19 @@ export declare class MigrationStore {
134
149
  kind: MigrationKind;
135
150
  at?: string;
136
151
  }): Promise<AppendResult>;
137
- /** 读取全部合法历史条目(旧→新;损坏/非史文件跳过并计数)。 */
138
- read(): Promise<ReadMigrationResult>;
152
+ /**
153
+ * 读取合法历史条目(旧→新;损坏/非史文件跳过并计数)。
154
+ *
155
+ * limit>0 时只读**最近 limit 条**(按文件名排序的尾部窗口)——首屏只要最近几十条活动,
156
+ * 整目录 readFile+parse 是历史目录唯一的慢点(真机 2360 条 ≈ 650 ms 纯 IO/解析,
157
+ * 叠上全量 JSON 回传即首页骨架 ~9.7 s 冷启动)。total 恒为目录内合法文件总数,
158
+ * 调用方据此区分「共 N 条,本页只含最近 M 条」。
159
+ */
160
+ read(opts?: {
161
+ limit?: number;
162
+ }): Promise<ReadMigrationResult>;
163
+ /** 目录内合法历史文件总数(只 readdir,不读文件内容;供「自动清理」行展示)。 */
164
+ count(): Promise<number>;
139
165
  /**
140
166
  * 保留清理:按文件名排序删除最旧合法历史文件,幂等。只删合法历史文件(防误删)。
141
167
  * 返回本次删除的文件名。
@@ -36,6 +36,26 @@ export const MIGRATION_HISTORY_SCHEMA_VERSION = 1;
36
36
  export const MIGRATION_HISTORY_DIR = 'migration-history';
37
37
  /** 默认保留上限(retention 删最旧)。 */
38
38
  export const DEFAULT_MIGRATION_RETENTION = 1000;
39
+ /** 用户可配置的保留上限区间(0 = 不限制;上限防「一次填 10 亿」把 UI 输入当系统限制用)。 */
40
+ export const HISTORY_RETENTION_MIN = 0;
41
+ export const HISTORY_RETENTION_MAX = 100_000;
42
+ /**
43
+ * 保留上限字面量校验(路由/偏好共用的唯一口径):只接受区间内的整数。
44
+ * 非法(字符串 / 小数 / 负数 / 越界)一律 false —— 调用方不得自行 Math.trunc 后放行。
45
+ */
46
+ export function isValidHistoryRetention(value) {
47
+ return typeof value === 'number'
48
+ && Number.isInteger(value)
49
+ && value >= HISTORY_RETENTION_MIN
50
+ && value <= HISTORY_RETENTION_MAX;
51
+ }
52
+ /**
53
+ * 有效保留上限:用户配置值合法则用它,否则回落默认(1000)。
54
+ * 0 = 不限制(由 retention 自己短路),缺省/损坏 → 默认档。
55
+ */
56
+ export function resolveHistoryRetention(configured) {
57
+ return isValidHistoryRetention(configured) ? configured : DEFAULT_MIGRATION_RETENTION;
58
+ }
39
59
  /** 文件名正则:`<stamp>-<hex12>.<kind>.json`,只认合法历史文件。 */
40
60
  const HISTORY_BASENAME_RE = /^[0-9A-Za-z:.+-]{8,}-[0-9a-f]{12}\.[a-z-]+\.json$/i;
41
61
  const TMP_PREFIX = '.dshcm.';
@@ -262,13 +282,22 @@ export class MigrationStore {
262
282
  return { ok: false, entry, error: error instanceof Error ? error.message : String(error) };
263
283
  }
264
284
  }
265
- /** 读取全部合法历史条目(旧→新;损坏/非史文件跳过并计数)。 */
266
- async read() {
285
+ /**
286
+ * 读取合法历史条目(旧→新;损坏/非史文件跳过并计数)。
287
+ *
288
+ * limit>0 时只读**最近 limit 条**(按文件名排序的尾部窗口)——首屏只要最近几十条活动,
289
+ * 整目录 readFile+parse 是历史目录唯一的慢点(真机 2360 条 ≈ 650 ms 纯 IO/解析,
290
+ * 叠上全量 JSON 回传即首页骨架 ~9.7 s 冷启动)。total 恒为目录内合法文件总数,
291
+ * 调用方据此区分「共 N 条,本页只含最近 M 条」。
292
+ */
293
+ async read(opts = {}) {
267
294
  const names = await this.io.readdirNames(this.dir).catch(() => []);
268
295
  const entries = [];
269
296
  const corrupted = [];
270
297
  const sorted = names.filter(isHistoryBasename).sort();
271
- for (const name of sorted) {
298
+ const limit = opts.limit !== undefined && Number.isInteger(opts.limit) ? opts.limit : 0;
299
+ const window = limit > 0 && sorted.length > limit ? sorted.slice(sorted.length - limit) : sorted;
300
+ for (const name of window) {
272
301
  const p = path.join(this.dir, name);
273
302
  let text;
274
303
  try {
@@ -289,7 +318,12 @@ export class MigrationStore {
289
318
  }
290
319
  entries.push(parsed);
291
320
  }
292
- return { entries, corrupted };
321
+ return { entries, corrupted, total: sorted.length };
322
+ }
323
+ /** 目录内合法历史文件总数(只 readdir,不读文件内容;供「自动清理」行展示)。 */
324
+ async count() {
325
+ const names = await this.io.readdirNames(this.dir).catch(() => []);
326
+ return names.filter(isHistoryBasename).length;
293
327
  }
294
328
  /**
295
329
  * 保留清理:按文件名排序删除最旧合法历史文件,幂等。只删合法历史文件(防误删)。
@@ -298,6 +332,9 @@ export class MigrationStore {
298
332
  async retention(limit = DEFAULT_MIGRATION_RETENTION) {
299
333
  const names = (await this.io.readdirNames(this.dir).catch(() => [])).filter(isHistoryBasename).sort();
300
334
  const removed = [];
335
+ // 0(或负数)= 不限制:调用方显式关闭自动清理时按「保留全部」处理,绝不当作「删光」。
336
+ if (!Number.isFinite(limit) || limit <= 0)
337
+ return removed;
301
338
  if (names.length <= limit)
302
339
  return removed;
303
340
  const toRemove = names.slice(0, names.length - limit);
package/lib/index.d.ts CHANGED
@@ -77,7 +77,7 @@ export declare const name = "config-manager";
77
77
  /** Services required before the engine can mount (present in every profile). */
78
78
  export declare const inject: string[];
79
79
  /** Plugin version, kept in sync with package.json ("version"). */
80
- export declare const PLUGIN_VERSION = "0.3.1";
80
+ export declare const PLUGIN_VERSION = "0.4.0";
81
81
  /**
82
82
  * Star 引导弹窗指向的 GitHub 仓库(用户引导点 Star 的目标)。
83
83
  * 与 package.json 的 repository 字段保持一致;界面不可改(硬编码,参照
@@ -130,7 +130,7 @@ export interface Config {
130
130
  /**
131
131
  * 本文件保留的 7 条路由的路径(被源码级守卫按文件窗口钉住,见下方 routesList 注释)。
132
132
  *
133
- * 其余 76 条路由的路径**声明在各自的组文件里**(src/routes/*.ts 的 endpoint({ path, methods }))——
133
+ * 其余 77 条路由的路径**声明在各自的组文件里**(src/routes/*.ts 的 endpoint({ path, methods }))——
134
134
  * 新增一条 API 只需那一条声明,不再有「常量表 + 路由对象」两处要同步。
135
135
  */
136
136
  export declare const API: {
package/lib/index.js CHANGED
@@ -62,6 +62,7 @@ import { JournalStore } from './core/journal.js';
62
62
  import { RunRegistry } from './core/run-registry.js';
63
63
  import { registerModelTools } from './core/model-tools.js';
64
64
  import { msgOf, zhMsg } from './core/messages.js';
65
+ import { createExitLockReleaser, reclaimStaleLockAtStartup } from './core/env-lock-lifecycle.js';
65
66
  import { engineMsg, getEngineLocale, setEngineLanguageSource, setEngineLocale } from './core/engine-locale.js';
66
67
  import { RollbackAutoTracker, RollbackPointEngine, ROLLBACK_POINTS_DIR_NAME, rollbackSessionBindingOf, rollbackTrackedEventOf } from './core/rollback-point.js';
67
68
  import { ROLLBACK_ATTRIBUTION_FILE_NAME, RollbackWriteAttribution } from './core/rollback-attribution.js';
@@ -100,12 +101,13 @@ import { SyncSessionStore } from './sync/sync-session.js';
100
101
  import { AutoSyncScheduler } from './sync/autosync-scheduler.js';
101
102
  import { BackupScheduler } from './sync/backup-scheduler.js';
102
103
  import { readBackupSchedule } from './sync/backup-schedule-config.js';
103
- import { readRollbackEnabledSync } from './sync/ui-prefs.js';
104
+ import { readRollbackEnabledSync, readUiPrefs } from './sync/ui-prefs.js';
104
105
  import { AUTO_BACKUP_PREFIX, isValidExportFileName, resolveNonCollidingExportName, writeBackupNote } from './sync/backup-files.js';
105
106
  import { DEFAULT_RETENTION_POLICY, selectPruneCandidatesByPolicy } from './sync/retention-policy.js';
106
107
  import { selectPruneCandidates } from './core/backup.js';
107
108
  import { appendAutosyncEntry } from './sync/sync-history.js';
108
109
  import { MigrationStore, MIGRATION_HISTORY_DIR } from './core/migration-history.js';
110
+ import { createHistoryPruner } from './core/history-prune.js';
109
111
  import { validateRepoUrl, validateWebDavUrl, isWebDavConfig, isS3Config, isGistConfig, channelOf, parseSyncChannel, SYNC_CHANNELS, GIST_PROVIDER, isS3CompatProvider, validateCloudChannelInput, cloudSecretRef } from './sync/sync-config.js';
110
112
  import { resolveSessionFormatDisposition, sessionFormatAbortResponse, } from './routes/session-format.js';
111
113
  import { createPrepareSync } from './sync/config-issue-reporting.js';
@@ -137,7 +139,7 @@ export const name = 'config-manager';
137
139
  /** Services required before the engine can mount (present in every profile). */
138
140
  export const inject = ['settings', 'credentials'];
139
141
  /** Plugin version, kept in sync with package.json ("version"). */
140
- export const PLUGIN_VERSION = '0.3.1';
142
+ export const PLUGIN_VERSION = '0.4.0';
141
143
  /** Plugin own package name — excluded from its own exported plugins list. */
142
144
  const PLUGIN_NAME = 'dsh-config-manager';
143
145
  /**
@@ -159,7 +161,7 @@ export const DEFAULT_GITHUB_CLIENT_ID = 'Ov23liq4i7n8UsylGRfb';
159
161
  /**
160
162
  * 本文件保留的 7 条路由的路径(被源码级守卫按文件窗口钉住,见下方 routesList 注释)。
161
163
  *
162
- * 其余 76 条路由的路径**声明在各自的组文件里**(src/routes/*.ts 的 endpoint({ path, methods }))——
164
+ * 其余 77 条路由的路径**声明在各自的组文件里**(src/routes/*.ts 的 endpoint({ path, methods }))——
163
165
  * 新增一条 API 只需那一条声明,不再有「常量表 + 路由对象」两处要同步。
164
166
  */
165
167
  export const API = {
@@ -2225,6 +2227,9 @@ function makeRoutes(deps) {
2225
2227
  */
2226
2228
  const resolveDisposition = (raw) => resolveSessionFormatDisposition(syncDir, raw);
2227
2229
  const dispositionAbort = (plan, disposition) => sessionFormatAbortResponse(plan, disposition, msg);
2230
+ // 迁移历史自动清理(语义/节流/为何不写审计条目 → src/core/history-prune.ts 头注释):启动清一次 + 写入后节流触发。
2231
+ const pruneHistory = createHistoryPruner({ history, log: host.log, readRetentionLimit: async () => (await readUiPrefs(syncDir)).historyRetentionMaxEntries });
2232
+ void pruneHistory('startup');
2228
2233
  /**
2229
2234
  * Phase 6:迁移历史 best-effort 追加(写失败不阻断操作,但记录/降级,不静默丢)。
2230
2235
  * 所有 destructive/migration 结果确定后调用。历史写盘 ms 级,失败仅日志 + 可选告警字段。
@@ -2236,6 +2241,8 @@ function makeRoutes(deps) {
2236
2241
  host.log.warn('迁移历史写入失败', { kind: raw.kind, error: res.error });
2237
2242
  return res.error;
2238
2243
  }
2244
+ // 写入成功后异步清理(不 await:历史写盘不应被保留策略拖慢)
2245
+ void pruneHistory('append');
2239
2246
  return undefined;
2240
2247
  }
2241
2248
  catch (error) {
@@ -3017,7 +3024,7 @@ function makeRoutes(deps) {
3017
3024
  /**
3018
3025
  * 路由表:本文件只保留被源码级守卫按**文件窗口**钉住的 7 条(host-entry 审计 F-04 记录的
3019
3026
  * tests/host/**、src/core/model-tools.test.ts、src/core/phase1-wiring.test.ts 的窗口断言)。
3020
- * 其余 76 条已按域拆到 src/routes/*.ts,由 buildRoutes 组装。
3027
+ * 其余 77 条已按域拆到 src/routes/*.ts,由 buildRoutes 组装。
3021
3028
  * 注册顺序不影响匹配:命名路由必须互不相同(webServer 契约)。
3022
3029
  */
3023
3030
  const routeEnv = makeRouteEnv();
@@ -3585,7 +3592,8 @@ export function apply(ctx, config) {
3585
3592
  const envLockManager = host.mutationLock;
3586
3593
  // Phase 3:启动 reconcile(只读)+ SAFE MODE。宿主 apply() 为同步 →
3587
3594
  // ① 先同步探测 durable SAFE MODE 标记(scheduler.start() 前即被阻断),
3588
- // ② 再异步跑完整只读 reconcile,刷新标志与 durable 标记。不自动 recover stale lock(Rev 3 P1-NEW-2)。
3595
+ // ② 再异步跑完整只读 reconcile,刷新标志与 durable 标记。
3596
+ // 残留锁:只对**结构性可证** stale 自动回收(判定与理由见 core/env-lock-lifecycle.ts)。
3589
3597
  // Phase 4 F21/F11:注入真实 snapshotExists 正向校验——journal 引用的 snapshot 存在 + READY +
3590
3598
  // verified(manifest/blob hash)+ op/env/owner binding 匹配 journal,才视为可回滚的有效 recovery 证据。
3591
3599
  const phase3Recovery = new Phase3Recovery({
@@ -3647,12 +3655,14 @@ export function apply(ctx, config) {
3647
3655
  });
3648
3656
  const { state } = await startupState.classify();
3649
3657
  startupStateResolved = true;
3658
+ // 残留锁自愈(可证 stale 回收 + 孤儿心跳清理),判定与理由见 core/env-lock-lifecycle.ts。
3659
+ const effectiveLockState = await reclaimStaleLockAtStartup({ kind: state.kind, inspected: lockInsp.state, lock: envLockManager, log: host.log });
3650
3660
  // issue #87:分类结论才是本轮权威。NORMAL 且没有活锁者 ⇒ 上一轮留下的 durable SAFE MODE 是**陈旧标记**
3651
3661
  // (没有任何未决 journal 能解释它),必须连内存标志一起复位:只复位内存会让本会话写操作继续被 423 挡着
3652
3662
  // (界面却说「无待处理事项」),只复位标记又会在下一次 probe 时重新置起(标记跨重启生效)。
3653
3663
  const safeModeVerdict = resolveStartupSafeMode({
3654
3664
  kind: state.kind,
3655
- lockState: mapLockStateForStartup(lockInsp.state),
3665
+ lockState: effectiveLockState,
3656
3666
  currentlyBlocked: phase3Recovery.safeModeActive,
3657
3667
  });
3658
3668
  phase3Recovery.safeModeActive = safeModeVerdict.blocked;
@@ -3839,6 +3849,14 @@ export function apply(ctx, config) {
3839
3849
  // 自动同步调度器随插件生命周期停止:插件重载/卸载时清理定时器,
3840
3850
  // 避免旧调度器残留导致重复后台同步。
3841
3851
  ctx.effect(() => () => scheduler.stop(), 'config-manager: autosync scheduler');
3852
+ // 退出兜底释放环境锁:关窗时若后台同步正在跑,各入口的 finally 等不到 ⇒ 锁留盘(见 core/env-lock-lifecycle.ts)。
3853
+ // 强杀 / 崩溃 / 断电仍靠下次启动的自动回收兜底。
3854
+ const releaseLockOnExit = createExitLockReleaser(envLockManager);
3855
+ process.once('exit', releaseLockOnExit);
3856
+ ctx.effect(() => () => {
3857
+ process.removeListener('exit', releaseLockOnExit);
3858
+ releaseLockOnExit();
3859
+ }, 'config-manager: environment lock exit release');
3842
3860
  // m-profiles:实例心跳(自报 + 定期刷新);dispose 时撤回自己的心跳文件,别让别人把死实例当成活的。
3843
3861
  ctx.effect(() => {
3844
3862
  const stopHeartbeat = profileRuntime.startHeartbeat();
@@ -4,22 +4,41 @@
4
4
  * W1(host-entry#F-02/#F-03):路由只在这里声明一次 —— endpoint({ path, methods }, handler) 的
5
5
  * path/methods 就是唯一声明处;围栏、方法判定与顶层异常处理由 src/routes/kit.ts 在注册点统一提供。
6
6
  */
7
- import { endpoint, writeJson } from './kit.js';
8
- import { parseHistoryQuery, queryHistory, renderExport, summarizeHistory } from '../core/migration-history.js';
7
+ import { endpoint, requireJsonObject, writeJson } from './kit.js';
8
+ import { DEFAULT_MIGRATION_RETENTION, HISTORY_RETENTION_MAX, HISTORY_RETENTION_MIN, isValidHistoryRetention, parseHistoryQuery, queryHistory, renderExport, resolveHistoryRetention, summarizeHistory, } from '../core/migration-history.js';
9
+ import { readUiPrefs, updateUiPrefs } from '../sync/ui-prefs.js';
10
+ /** 列表接口的 limit 上限:防「?limit=99999999」把只读端点的读放大成拒绝服务面。 */
11
+ const HISTORY_LIST_LIMIT_MAX = 5000;
12
+ /**
13
+ * 解析列表请求的 limit:缺省 / 非法 / 负数 = 0(= 全量,老口径不变);超上限按上限截断。
14
+ * 只接受十进制整数字面量(parseInt 会把 '12abc' 读成 12,故先用正则判形)。
15
+ */
16
+ function parseListLimit(raw) {
17
+ if (raw === null || !/^\d+$/.test(raw.trim()))
18
+ return 0;
19
+ const n = Number.parseInt(raw.trim(), 10);
20
+ if (!Number.isFinite(n) || n <= 0)
21
+ return 0;
22
+ return Math.min(n, HISTORY_LIST_LIMIT_MAX);
23
+ }
9
24
  export function historyRoutes(env) {
10
- const { history, host, } = env;
25
+ const { history, host, msg, syncDir, withMutationGate, } = env;
11
26
  return [
12
27
  // ------------------------------------------------------------ history
13
28
  // Phase 6:迁移历史审计(统一历史引擎)。只读 GET:列表(过滤)+ 导出。
14
29
  // loopback fence(guard)与全仓一致——仅同源 + loopback 可访问。
30
+ // ?limit=N:只读最近 N 条(文件名尾部窗口)。首页只要最近几十条活动,全量读 + 全量回传
31
+ // 会把首屏骨架拖到秒级(真机 2360 条:纯 IO/解析 650 ms,冷启动含回传 9.7 s)。
32
+ // 响应始终带 total(目录合法文件总数)与 scanned(本次实际读取条数),避免 UI 把窗口当全量。
15
33
  endpoint({ path: '/api/dsh-config-manager/history', methods: ['GET'] }, async (req, res) => {
16
34
  try {
17
35
  const url = new URL(req.url ?? '/', 'http://localhost');
18
36
  const q = parseHistoryQuery(Object.fromEntries(url.searchParams));
19
- const { entries, corrupted } = await history.read();
37
+ const limit = parseListLimit(url.searchParams.get('limit'));
38
+ const { entries, corrupted, total } = await history.read({ limit });
20
39
  const filtered = queryHistory(entries, q);
21
40
  const stats = summarizeHistory(filtered);
22
- writeJson(res, 200, { ok: true, entries: filtered, stats, corrupted });
41
+ writeJson(res, 200, { ok: true, entries: filtered, stats, corrupted, total: total ?? entries.length, scanned: entries.length, limit });
23
42
  }
24
43
  catch (error) {
25
44
  writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) });
@@ -48,6 +67,52 @@ export function historyRoutes(env) {
48
67
  writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) });
49
68
  }
50
69
  }),
70
+ // ------------------------------------------------------ history/retention
71
+ // 迁移历史自动清理(issue:历史目录只增不减,真机已 2360 条 / 0.67 MB)。
72
+ // 策略存 ui-prefs.json 的 historyRetentionMaxEntries(0 = 不限制,缺省 1000);
73
+ // 宿主在每次写入历史后按该值节流清理最旧条目(调度与取舍 → src/core/history-prune.ts)。
74
+ // GET → 当前策略 + 目录现状;POST → 改策略并立即清理一次(同一道写入门)。
75
+ // 一条 exact 路由 + 方法内部分发:webserver 对重复 (kind, path) 直接抛错。
76
+ endpoint({ path: '/api/dsh-config-manager/history/retention', methods: ['GET', 'POST'] }, async (req, res) => {
77
+ if (req.method === 'GET') {
78
+ try {
79
+ const [prefs, total] = await Promise.all([readUiPrefs(syncDir), history.count()]);
80
+ writeJson(res, 200, {
81
+ ok: true,
82
+ maxEntries: resolveHistoryRetention(prefs.historyRetentionMaxEntries),
83
+ total,
84
+ defaultMaxEntries: DEFAULT_MIGRATION_RETENTION,
85
+ allowedMin: HISTORY_RETENTION_MIN,
86
+ allowedMax: HISTORY_RETENTION_MAX,
87
+ });
88
+ }
89
+ catch (error) {
90
+ writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) });
91
+ }
92
+ return;
93
+ }
94
+ // 写分支:删历史属破坏性操作,与其它写路径同一道门(不写审计条目 → 见 history-prune 头注释)。
95
+ await withMutationGate('history-retention', async (gatedReq, gatedRes) => {
96
+ const body = await requireJsonObject(gatedReq);
97
+ const next = body['maxEntries'];
98
+ if (!isValidHistoryRetention(next)) {
99
+ writeJson(gatedRes, 400, {
100
+ ok: false,
101
+ code: 'invalid-retention',
102
+ error: msg('route.historyRetentionInvalid', { min: HISTORY_RETENTION_MIN, max: HISTORY_RETENTION_MAX }),
103
+ });
104
+ return;
105
+ }
106
+ // 先落策略再清理:清理失败也要让新策略生效(下一次写入会重试),否则用户改完不生效。
107
+ await updateUiPrefs(syncDir, { historyRetentionMaxEntries: next });
108
+ const removed = next > 0 ? await history.retention(next) : [];
109
+ const total = await history.count();
110
+ if (removed.length > 0) {
111
+ host.log.info('迁移历史自动清理', { maxEntries: next, removed: removed.length, total });
112
+ }
113
+ writeJson(gatedRes, 200, { ok: true, maxEntries: next, removed: removed.length, total });
114
+ }, { journaled: false })(req, res);
115
+ }),
51
116
  ];
52
117
  }
53
118
  //# sourceMappingURL=history.js.map
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * 顺序对匹配无影响:DSH webServer 的契约是「命名路由必须互不相同,注册顺序不影响请求」
5
5
  * (见 @deepseek-ai/dsh-host-webserver 的 WebServer 文档)。src/index.ts 保留的 7 条被源码级
6
- * 守卫按文件窗口钉住,其余 76 条在这里组装(总数 83:含 path-browse)。
6
+ * 守卫按文件窗口钉住,其余 77 条在这里组装(总数 84:含 path-browse)。
7
7
  */
8
8
  import type { WebRoute } from './kit.ts';
9
9
  import type { RoutesEnv } from './context.ts';
@@ -8,8 +8,8 @@
8
8
  * - 「每条路由首行 guard」这条安全不变量此前**只写在注释里**,零测试覆盖;
9
9
  * - 3 条 prefix 路由自造围栏(裸 isLoopbackRequest + 自判方法)。
10
10
  *
11
- * 计数口径(三路一致 = 83,勿再照抄旧审计初稿的计数 —— 那是计数口径 overcount):
12
- * 路由快照 83 条 = 现行 `endpoint()` 声明 83 条 = 运行期 `buildRoutes()` 76 条 + `src/index.ts` 保留的 7 条。
11
+ * 计数口径(三路一致 = 84,勿再照抄旧审计初稿的计数 —— 那是计数口径 overcount):
12
+ * 路由快照 84 条 = 现行 `endpoint()` 声明 84 条 = 运行期 `buildRoutes()` 77 条 + `src/index.ts` 保留的 7 条。
13
13
  * 增删路由后必须同步这段计数、`src/routes/index.ts` 的头注释与 parity 快照清单;`tests/route/route-parity.test.ts`
14
14
  * 的「路由计数散文」守卫会拿真实声明数逐条对账(写错即红灯)。
15
15
  *
@@ -6,6 +6,7 @@ export declare const zh: {
6
6
  readonly 'route.importNoSections': '无分区';
7
7
  readonly 'route.importHistorySummary': '导入完成:{sections}(执行 {count} 项)';
8
8
  readonly 'route.importIncomplete': '导入未完全成功';
9
+ readonly 'route.historyRetentionInvalid': '保留上限必须是 {min}–{max} 之间的整数(0 = 不限制)';
9
10
  readonly 'route.profileLaunchSummary': '启动档案 {name}(独立实例 :{port})';
10
11
  readonly 'route.profileCreateSummary': '新建档案 {name}(模板 {template})';
11
12
  readonly 'route.profileCopySummary': '复制档案 {from} → {to}{suffix}';
@@ -21,6 +21,8 @@ export const zh = {
21
21
  'route.importNoSections': '无分区',
22
22
  'route.importHistorySummary': '导入完成:{sections}(执行 {count} 项)',
23
23
  'route.importIncomplete': '导入未完全成功',
24
+ // ---------- 迁移历史自动清理 ----------
25
+ 'route.historyRetentionInvalid': '保留上限必须是 {min}–{max} 之间的整数(0 = 不限制)',
24
26
  // ---------- 档案 ----------
25
27
  'route.profileLaunchSummary': '启动档案 {name}(独立实例 :{port})',
26
28
  'route.profileCreateSummary': '新建档案 {name}(模板 {template})',
@@ -64,6 +66,7 @@ export const en = {
64
66
  'route.importNoSections': 'no sections',
65
67
  'route.importHistorySummary': 'Import finished: {sections} ({count} item(s) executed)',
66
68
  'route.importIncomplete': 'Import did not fully succeed',
69
+ 'route.historyRetentionInvalid': 'Retention limit must be an integer between {min} and {max} (0 = unlimited)',
67
70
  'route.profileLaunchSummary': 'Launched profile {name} (separate instance :{port})',
68
71
  'route.profileCreateSummary': 'Created profile {name} (template {template})',
69
72
  'route.profileCopySummary': 'Copied profile {from} → {to}{suffix}',
@@ -440,6 +440,12 @@ export class AutoSyncScheduler {
440
440
  let releaseLock = null;
441
441
  if (this.mutationLock !== undefined) {
442
442
  try {
443
+ // 本轮开始前先自愈:上一轮异常退出留下的**可证** stale 残留锁只会让每轮静默 skip,
444
+ // 用户不重启就永远不同步。只删可证的(owner 确证死亡 / PID 复用),其余保持下面既有的 warn 路径。
445
+ try {
446
+ await this.mutationLock.reclaimProvableStaleLock?.();
447
+ }
448
+ catch { /* 预检失败不改变既有路径 */ }
443
449
  const lk = await withMutationLock(this.mutationLock, { op: 'autosync', target: channel, isBlocked: this.isBlocked });
444
450
  if (lk.context === null) {
445
451
  this.running = false;
@@ -153,6 +153,12 @@ export class BackupScheduler {
153
153
  return { status: 'skipped', skipReason: 'conflict', consecutiveFailures: cfg.consecutiveFailures };
154
154
  }
155
155
  try {
156
+ // 本轮开始前先自愈:可证的 stale 残留锁会让每轮备份直接 skipped,用户不重启就永远不备份。
157
+ // 只删可证的(owner 确证死亡 / PID 复用);不可证的仍走下面 runWithMutationLock 的 skipped 分支。
158
+ try {
159
+ await this.mutationLock?.reclaimProvableStaleLock?.();
160
+ }
161
+ catch { /* 预检失败不改变既有路径 */ }
156
162
  // Phase 2 锁:定时备份写入 exports 属 GLOBAL mutation(与 Sync push / 手动备份互斥)。
157
163
  // 无锁环境(测试)→ 不锁定直接执行;锁被占用 → 返回 failed(destructive 不执行)。
158
164
  const result = await runWithMutationLock(this.mutationLock, { op: 'backup-schedule', target: 'exports', isBlocked: this.isBlocked }, async (lockCtx) => {