dsh-config-manager 0.3.0 → 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 (78) hide show
  1. package/lib/client.d.ts +33 -1
  2. package/lib/client.js +1063 -838
  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/s3/oss4-verify.js +21 -6
  21. package/lib/sync/s3/s3-providers.d.ts +13 -0
  22. package/lib/sync/s3/s3-providers.js +6 -0
  23. package/lib/sync/s3/s3-transport.d.ts +22 -0
  24. package/lib/sync/s3/s3-transport.js +89 -18
  25. package/lib/sync/ui-prefs.d.ts +8 -0
  26. package/lib/sync/ui-prefs.js +8 -0
  27. package/lib/utils/env-lock.d.ts +55 -1
  28. package/lib/utils/env-lock.js +131 -2
  29. package/lib/utils/messages-utils.d.ts +3 -0
  30. package/lib/utils/messages-utils.js +6 -0
  31. package/package.json +1 -1
  32. package/src/client/common/InfoHint.tsx +12 -3
  33. package/src/client/common/Skeleton.tsx +45 -8
  34. package/src/client/common/info-hint-guard.test.ts +196 -0
  35. package/src/client/common/routes.ts +3 -1
  36. package/src/client/common/skeleton-guard.test.ts +58 -0
  37. package/src/client/common/ui.tsx +17 -4
  38. package/src/client/config-manager.module.css +256 -27
  39. package/src/client/css-motion-guard.test.ts +230 -0
  40. package/src/client/environment/EnvironmentPanel.tsx +41 -29
  41. package/src/client/environment/maintenance/DiskUsageCard.tsx +28 -33
  42. package/src/client/environment/profiles-incomplete-ui.test.ts +9 -5
  43. package/src/client/export/ExportView.tsx +6 -6
  44. package/src/client/history/HistoryPanel.tsx +87 -2
  45. package/src/client/history/history-api.ts +49 -3
  46. package/src/client/history/history-locales.ts +30 -0
  47. package/src/client/home/HomePanel.tsx +55 -23
  48. package/src/client/market/MyConfigsWizard.tsx +12 -3
  49. package/src/client/recovery/RecoveryPanel.tsx +93 -92
  50. package/src/client/recovery/RollbackCard.tsx +25 -16
  51. package/src/client/sync/AutosyncCard.tsx +12 -6
  52. package/src/client/sync/ChannelConfigDialog.tsx +45 -45
  53. package/src/client/sync/DecryptPasswordCard.tsx +3 -3
  54. package/src/client/sync/SecurityOptionsCard.tsx +3 -3
  55. package/src/client/sync/SyncSectionPickerDialog.tsx +3 -3
  56. package/src/core/env-lock-lifecycle.ts +73 -0
  57. package/src/core/history-prune.test.ts +115 -0
  58. package/src/core/history-prune.ts +61 -0
  59. package/src/core/index.ts +2 -0
  60. package/src/core/migration-history.test.ts +78 -0
  61. package/src/core/migration-history.ts +46 -4
  62. package/src/index.ts +25 -6
  63. package/src/routes/history.ts +81 -4
  64. package/src/routes/index.ts +1 -1
  65. package/src/routes/kit.ts +2 -2
  66. package/src/routes/messages.ts +3 -0
  67. package/src/sync/autosync-scheduler.ts +3 -0
  68. package/src/sync/backup-scheduler.ts +3 -0
  69. package/src/sync/s3/oss4-verify.ts +22 -6
  70. package/src/sync/s3/s3-conditional-write.test.ts +153 -3
  71. package/src/sync/s3/s3-providers.ts +20 -0
  72. package/src/sync/s3/s3-transport.oss4-server.test.ts +48 -0
  73. package/src/sync/s3/s3-transport.ts +98 -17
  74. package/src/sync/ui-prefs.test.ts +32 -0
  75. package/src/sync/ui-prefs.ts +16 -0
  76. package/src/utils/env-lock.test.ts +107 -0
  77. package/src/utils/env-lock.ts +124 -2
  78. package/src/utils/messages-utils.ts +6 -0
@@ -21,6 +21,8 @@ import {
21
21
  MigrationStore, sanitizeEntry, queryHistory, renderExport,
22
22
  parseHistoryQuery, isValidMigrationKind, redactHistoryText,
23
23
  makeHistoryFilename, isHistoryBasename,
24
+ isValidHistoryRetention, resolveHistoryRetention,
25
+ HISTORY_RETENTION_MIN, HISTORY_RETENTION_MAX, DEFAULT_MIGRATION_RETENTION,
24
26
  type StoredMigrationHistoryEntry, type MigrationIo,
25
27
  } from './migration-history.ts';
26
28
 
@@ -167,6 +169,82 @@ test('APPEND-ONLY:retention 不足 limit 时不做任何删除(幂等)', a
167
169
  assert.equal((await store.read()).entries.length, 1);
168
170
  });
169
171
 
172
+ test('APPEND-ONLY:retention(0) = 不限制,绝不清空目录', async (t) => {
173
+ const dir = tmp(t);
174
+ const store = mkStore(dir);
175
+ await store.append(makeRaw({ kind: 'import', at: '2026-08-30T12:00:00.000Z' }));
176
+ await store.append(makeRaw({ kind: 'restore', at: '2026-08-30T12:01:00.000Z' }));
177
+ // 0 是「不限制」而不是「保留 0 条」—— 把 0 当上限会把历史清空,属不可逆数据损失
178
+ assert.deepEqual(await store.retention(0), []);
179
+ assert.equal((await store.read()).entries.length, 2);
180
+ // 负数/NaN 同口径(防御非法策略值,绝不批量删)
181
+ assert.deepEqual(await store.retention(-1), []);
182
+ assert.deepEqual(await store.retention(Number.NaN), []);
183
+ assert.equal((await store.read()).entries.length, 2);
184
+ });
185
+
186
+ test('TAIL:read({ limit }) 只读最近 N 条,total 仍报目录全量', async (t) => {
187
+ const dir = tmp(t);
188
+ const store = mkStore(dir);
189
+ for (let i = 0; i < 6; i++) {
190
+ await store.append(makeRaw({ at: `2026-08-30T12:0${i}:00.000Z`, summary: `第 ${i} 条` }));
191
+ }
192
+ const tail = await store.read({ limit: 2 });
193
+ // 尾部窗口 = 最新 2 条(文件名按时间戳排序,12:04 / 12:05)
194
+ assert.equal(tail.entries.length, 2);
195
+ assert.equal(tail.entries[0]!.summary, '第 4 条');
196
+ assert.equal(tail.entries[1]!.summary, '第 5 条');
197
+ // total 是「目录里有多少」(首页窗口之外的旧条目仍要能报出规模)
198
+ assert.equal(tail.total, 6);
199
+ // limit 大于总数 / 未传 / 0 → 全量
200
+ assert.equal((await store.read({ limit: 99 })).entries.length, 6);
201
+ assert.equal((await store.read()).entries.length, 6);
202
+ assert.equal((await store.read({ limit: 0 })).entries.length, 6);
203
+ });
204
+
205
+ test('TAIL:read({ limit }) 不改统计口径——窗口内损坏条目照旧进 corrupted', async (t) => {
206
+ const dir = tmp(t);
207
+ const store = mkStore(dir);
208
+ await store.append(makeRaw({ at: '2026-08-30T12:00:00.000Z' }));
209
+ await store.append(makeRaw({ at: '2026-08-30T12:01:00.000Z' }));
210
+ const hist = path.join(dir, 'migration-history');
211
+ // 最新一条写坏(篡改内容 → contentHash 不匹配)
212
+ const newest = (fssync.readdirSync(hist).sort() as string[]).at(-1)!;
213
+ await fs.writeFile(path.join(hist, newest), '{ broken');
214
+ const res = await store.read({ limit: 1 });
215
+ assert.equal(res.entries.length, 0);
216
+ assert.equal(res.corrupted.length, 1);
217
+ assert.equal(res.total, 2);
218
+ });
219
+
220
+ test('COUNT:count() 只数合法历史文件,不读内容、不数脏文件', async (t) => {
221
+ const dir = tmp(t);
222
+ const store = mkStore(dir);
223
+ const hist = path.join(dir, 'migration-history');
224
+ await fs.mkdir(hist, { recursive: true });
225
+ await store.append(makeRaw());
226
+ await fs.writeFile(path.join(hist, 'leftover.txt'), 'junk');
227
+ await fs.writeFile(path.join(hist, '.dshcm.abc.tmp'), 'junk');
228
+ assert.equal(await store.count(), 1);
229
+ // 不存在的目录 → 0(首启还没写过历史)
230
+ assert.equal(await new MigrationStore({ dir: path.join(dir, 'nope') }).count(), 0);
231
+ });
232
+
233
+ test('RETENTION-POLICY:isValid/resolve 只收区间内整数,非法回落缺省 1000', () => {
234
+ assert.equal(isValidHistoryRetention(0), true);
235
+ assert.equal(isValidHistoryRetention(1000), true);
236
+ assert.equal(isValidHistoryRetention(HISTORY_RETENTION_MAX), true);
237
+ for (const bad of [-1, 1.5, HISTORY_RETENTION_MAX + 1, Number.NaN, '1000', null, undefined, {}]) {
238
+ assert.equal(isValidHistoryRetention(bad), false, String(bad));
239
+ }
240
+ assert.equal(resolveHistoryRetention(500), 500);
241
+ assert.equal(resolveHistoryRetention(0), 0);
242
+ assert.equal(resolveHistoryRetention(undefined), DEFAULT_MIGRATION_RETENTION);
243
+ assert.equal(resolveHistoryRetention(-5), DEFAULT_MIGRATION_RETENTION);
244
+ assert.equal(resolveHistoryRetention('oops'), DEFAULT_MIGRATION_RETENTION);
245
+ assert.equal(HISTORY_RETENTION_MIN, 0);
246
+ });
247
+
170
248
  test('APPEND-ONLY:无 update/delete API(导出不暴露改删符号)', () => {
171
249
  const exported = Object.keys(MigrationStore.prototype).filter((k) => /^(update|delete|remove|edit|overwrite)/.test(k));
172
250
  assert.deepEqual(exported, []);
@@ -39,6 +39,29 @@ export const MIGRATION_HISTORY_DIR = 'migration-history';
39
39
  /** 默认保留上限(retention 删最旧)。 */
40
40
  export const DEFAULT_MIGRATION_RETENTION = 1000;
41
41
 
42
+ /** 用户可配置的保留上限区间(0 = 不限制;上限防「一次填 10 亿」把 UI 输入当系统限制用)。 */
43
+ export const HISTORY_RETENTION_MIN = 0;
44
+ export const HISTORY_RETENTION_MAX = 100_000;
45
+
46
+ /**
47
+ * 保留上限字面量校验(路由/偏好共用的唯一口径):只接受区间内的整数。
48
+ * 非法(字符串 / 小数 / 负数 / 越界)一律 false —— 调用方不得自行 Math.trunc 后放行。
49
+ */
50
+ export function isValidHistoryRetention(value: unknown): value is number {
51
+ return typeof value === 'number'
52
+ && Number.isInteger(value)
53
+ && value >= HISTORY_RETENTION_MIN
54
+ && value <= HISTORY_RETENTION_MAX;
55
+ }
56
+
57
+ /**
58
+ * 有效保留上限:用户配置值合法则用它,否则回落默认(1000)。
59
+ * 0 = 不限制(由 retention 自己短路),缺省/损坏 → 默认档。
60
+ */
61
+ export function resolveHistoryRetention(configured: unknown): number {
62
+ return isValidHistoryRetention(configured) ? configured : DEFAULT_MIGRATION_RETENTION;
63
+ }
64
+
42
65
  /** 文件名正则:`<stamp>-<hex12>.<kind>.json`,只认合法历史文件。 */
43
66
  const HISTORY_BASENAME_RE = /^[0-9A-Za-z:.+-]{8,}-[0-9a-f]{12}\.[a-z-]+\.json$/i;
44
67
  const TMP_PREFIX = '.dshcm.';
@@ -120,6 +143,8 @@ export interface ReadMigrationResult {
120
143
  entries: StoredMigrationHistoryEntry[];
121
144
  /** 被跳过/损坏的文件名(读取时识别,UI 可选警示;不静默接受)。 */
122
145
  corrupted: string[];
146
+ /** 目录内**合法历史文件**总数(含被 limit 窗口挡在外的旧条目;未统计时为 undefined)。 */
147
+ total?: number;
123
148
  }
124
149
 
125
150
  /** 追加写入结果(best-effort 调用方据此判断降级)。 */
@@ -348,13 +373,22 @@ export class MigrationStore {
348
373
  }
349
374
  }
350
375
 
351
- /** 读取全部合法历史条目(旧→新;损坏/非史文件跳过并计数)。 */
352
- async read(): Promise<ReadMigrationResult> {
376
+ /**
377
+ * 读取合法历史条目(旧→新;损坏/非史文件跳过并计数)。
378
+ *
379
+ * limit>0 时只读**最近 limit 条**(按文件名排序的尾部窗口)——首屏只要最近几十条活动,
380
+ * 整目录 readFile+parse 是历史目录唯一的慢点(真机 2360 条 ≈ 650 ms 纯 IO/解析,
381
+ * 叠上全量 JSON 回传即首页骨架 ~9.7 s 冷启动)。total 恒为目录内合法文件总数,
382
+ * 调用方据此区分「共 N 条,本页只含最近 M 条」。
383
+ */
384
+ async read(opts: { limit?: number } = {}): Promise<ReadMigrationResult> {
353
385
  const names = await this.io.readdirNames(this.dir).catch(() => []);
354
386
  const entries: StoredMigrationHistoryEntry[] = [];
355
387
  const corrupted: string[] = [];
356
388
  const sorted = names.filter(isHistoryBasename).sort();
357
- for (const name of sorted) {
389
+ const limit = opts.limit !== undefined && Number.isInteger(opts.limit) ? opts.limit : 0;
390
+ const window = limit > 0 && sorted.length > limit ? sorted.slice(sorted.length - limit) : sorted;
391
+ for (const name of window) {
358
392
  const p = path.join(this.dir, name);
359
393
  let text: string;
360
394
  try {
@@ -368,7 +402,13 @@ export class MigrationStore {
368
402
  if (parsed === null) { corrupted.push(name); continue; }
369
403
  entries.push(parsed);
370
404
  }
371
- return { entries, corrupted };
405
+ return { entries, corrupted, total: sorted.length };
406
+ }
407
+
408
+ /** 目录内合法历史文件总数(只 readdir,不读文件内容;供「自动清理」行展示)。 */
409
+ async count(): Promise<number> {
410
+ const names = await this.io.readdirNames(this.dir).catch(() => []);
411
+ return names.filter(isHistoryBasename).length;
372
412
  }
373
413
 
374
414
  /**
@@ -378,6 +418,8 @@ export class MigrationStore {
378
418
  async retention(limit = DEFAULT_MIGRATION_RETENTION): Promise<string[]> {
379
419
  const names = (await this.io.readdirNames(this.dir).catch(() => [])).filter(isHistoryBasename).sort();
380
420
  const removed: string[] = [];
421
+ // 0(或负数)= 不限制:调用方显式关闭自动清理时按「保留全部」处理,绝不当作「删光」。
422
+ if (!Number.isFinite(limit) || limit <= 0) return removed;
381
423
  if (names.length <= limit) return removed;
382
424
  const toRemove = names.slice(0, names.length - limit);
383
425
  for (const name of toRemove) {
package/src/index.ts CHANGED
@@ -76,6 +76,7 @@ import { JournalStore } from './core/journal.ts'
76
76
  import { RunRegistry, type RunState } from './core/run-registry.ts'
77
77
  import { registerModelTools } from './core/model-tools.ts'
78
78
  import { msgOf, zhMsg } from './core/messages.ts'
79
+ import { createExitLockReleaser, reclaimStaleLockAtStartup } from './core/env-lock-lifecycle.ts'
79
80
  import { engineMsg, getEngineLocale, setEngineLanguageSource, setEngineLocale } from './core/engine-locale.ts'
80
81
  import { RollbackAutoTracker, RollbackPointEngine, ROLLBACK_POINTS_DIR_NAME, rollbackSessionBindingOf, rollbackTrackedEventOf } from './core/rollback-point.ts'
81
82
  import { ROLLBACK_ATTRIBUTION_FILE_NAME, RollbackWriteAttribution } from './core/rollback-attribution.ts'
@@ -124,7 +125,7 @@ import { SyncSessionStore } from './sync/sync-session.ts'
124
125
  import { AutoSyncScheduler } from './sync/autosync-scheduler.ts'
125
126
  import { BackupScheduler } from './sync/backup-scheduler.ts'
126
127
  import { readBackupSchedule } from './sync/backup-schedule-config.ts'
127
- import { readRollbackEnabledSync } from './sync/ui-prefs.ts'
128
+ import { readRollbackEnabledSync, readUiPrefs } from './sync/ui-prefs.ts'
128
129
  import { AUTO_BACKUP_PREFIX, isValidExportFileName, resolveNonCollidingExportName, writeBackupNote } from './sync/backup-files.ts'
129
130
  import { DEFAULT_RETENTION_POLICY, selectPruneCandidatesByPolicy } from './sync/retention-policy.ts'
130
131
  import type { RetentionPolicy } from './sync/retention-policy.ts'
@@ -132,6 +133,7 @@ import type { PruneSelector } from './core/backup.ts'
132
133
  import { selectPruneCandidates } from './core/backup.ts'
133
134
  import { appendAutosyncEntry } from './sync/sync-history.ts'
134
135
  import { MigrationStore, type MigrationKind, type MigrationResult, MIGRATION_HISTORY_DIR } from './core/migration-history.ts'
136
+ import { createHistoryPruner } from './core/history-prune.ts'
135
137
  import { validateRepoUrl, validateWebDavUrl, isWebDavConfig, isS3Config, isGistConfig, channelOf, parseSyncChannel, SYNC_CHANNELS, GIST_PROVIDER, isS3CompatProvider, validateCloudChannelInput, cloudSecretRef } from './sync/sync-config.ts'
136
138
  import {
137
139
  resolveSessionFormatDisposition,
@@ -181,7 +183,7 @@ export const name = 'config-manager'
181
183
  export const inject = ['settings', 'credentials']
182
184
 
183
185
  /** Plugin version, kept in sync with package.json ("version"). */
184
- export const PLUGIN_VERSION = '0.3.0'
186
+ export const PLUGIN_VERSION = '0.4.0'
185
187
 
186
188
  /** Plugin own package name — excluded from its own exported plugins list. */
187
189
  const PLUGIN_NAME = 'dsh-config-manager'
@@ -246,7 +248,7 @@ export interface Config {
246
248
  /**
247
249
  * 本文件保留的 7 条路由的路径(被源码级守卫按文件窗口钉住,见下方 routesList 注释)。
248
250
  *
249
- * 其余 76 条路由的路径**声明在各自的组文件里**(src/routes/*.ts 的 endpoint({ path, methods }))——
251
+ * 其余 77 条路由的路径**声明在各自的组文件里**(src/routes/*.ts 的 endpoint({ path, methods }))——
250
252
  * 新增一条 API 只需那一条声明,不再有「常量表 + 路由对象」两处要同步。
251
253
  */
252
254
  export const API = {
@@ -2545,6 +2547,10 @@ function makeRoutes(deps: RoutesDeps): { routes: WebRoute[]; scheduler: AutoSync
2545
2547
  const dispositionAbort = (plan: ImportPlan, disposition: SessionFormatDisposition): SessionFormatAbortBody | null =>
2546
2548
  sessionFormatAbortResponse(plan, disposition, msg)
2547
2549
 
2550
+ // 迁移历史自动清理(语义/节流/为何不写审计条目 → src/core/history-prune.ts 头注释):启动清一次 + 写入后节流触发。
2551
+ const pruneHistory = createHistoryPruner({ history, log: host.log, readRetentionLimit: async () => (await readUiPrefs(syncDir)).historyRetentionMaxEntries })
2552
+ void pruneHistory('startup')
2553
+
2548
2554
  /**
2549
2555
  * Phase 6:迁移历史 best-effort 追加(写失败不阻断操作,但记录/降级,不静默丢)。
2550
2556
  * 所有 destructive/migration 结果确定后调用。历史写盘 ms 级,失败仅日志 + 可选告警字段。
@@ -2558,6 +2564,8 @@ function makeRoutes(deps: RoutesDeps): { routes: WebRoute[]; scheduler: AutoSync
2558
2564
  host.log.warn('迁移历史写入失败', { kind: raw.kind, error: res.error })
2559
2565
  return res.error
2560
2566
  }
2567
+ // 写入成功后异步清理(不 await:历史写盘不应被保留策略拖慢)
2568
+ void pruneHistory('append')
2561
2569
  return undefined
2562
2570
  } catch (error) {
2563
2571
  host.log.warn('迁移历史写入异常', { kind: raw.kind, error: error instanceof Error ? error.message : String(error) })
@@ -3341,7 +3349,7 @@ function makeRoutes(deps: RoutesDeps): { routes: WebRoute[]; scheduler: AutoSync
3341
3349
  /**
3342
3350
  * 路由表:本文件只保留被源码级守卫按**文件窗口**钉住的 7 条(host-entry 审计 F-04 记录的
3343
3351
  * tests/host/**、src/core/model-tools.test.ts、src/core/phase1-wiring.test.ts 的窗口断言)。
3344
- * 其余 76 条已按域拆到 src/routes/*.ts,由 buildRoutes 组装。
3352
+ * 其余 77 条已按域拆到 src/routes/*.ts,由 buildRoutes 组装。
3345
3353
  * 注册顺序不影响匹配:命名路由必须互不相同(webServer 契约)。
3346
3354
  */
3347
3355
  const routeEnv: RouteEnvInferred = makeRouteEnv()
@@ -3891,7 +3899,8 @@ export function apply(ctx: Context, config?: Config): void {
3891
3899
  const envLockManager = host.mutationLock as EnvironmentLockManager
3892
3900
  // Phase 3:启动 reconcile(只读)+ SAFE MODE。宿主 apply() 为同步 →
3893
3901
  // ① 先同步探测 durable SAFE MODE 标记(scheduler.start() 前即被阻断),
3894
- // ② 再异步跑完整只读 reconcile,刷新标志与 durable 标记。不自动 recover stale lock(Rev 3 P1-NEW-2)。
3902
+ // ② 再异步跑完整只读 reconcile,刷新标志与 durable 标记。
3903
+ // 残留锁:只对**结构性可证** stale 自动回收(判定与理由见 core/env-lock-lifecycle.ts)。
3895
3904
  // Phase 4 F21/F11:注入真实 snapshotExists 正向校验——journal 引用的 snapshot 存在 + READY +
3896
3905
  // verified(manifest/blob hash)+ op/env/owner binding 匹配 journal,才视为可回滚的有效 recovery 证据。
3897
3906
  const phase3Recovery = new Phase3Recovery({
@@ -3945,12 +3954,14 @@ export function apply(ctx: Context, config?: Config): void {
3945
3954
  })
3946
3955
  const { state } = await startupState.classify()
3947
3956
  startupStateResolved = true
3957
+ // 残留锁自愈(可证 stale 回收 + 孤儿心跳清理),判定与理由见 core/env-lock-lifecycle.ts。
3958
+ const effectiveLockState = await reclaimStaleLockAtStartup({ kind: state.kind, inspected: lockInsp.state, lock: envLockManager, log: host.log })
3948
3959
  // issue #87:分类结论才是本轮权威。NORMAL 且没有活锁者 ⇒ 上一轮留下的 durable SAFE MODE 是**陈旧标记**
3949
3960
  // (没有任何未决 journal 能解释它),必须连内存标志一起复位:只复位内存会让本会话写操作继续被 423 挡着
3950
3961
  // (界面却说「无待处理事项」),只复位标记又会在下一次 probe 时重新置起(标记跨重启生效)。
3951
3962
  const safeModeVerdict = resolveStartupSafeMode({
3952
3963
  kind: state.kind,
3953
- lockState: mapLockStateForStartup(lockInsp.state),
3964
+ lockState: effectiveLockState,
3954
3965
  currentlyBlocked: phase3Recovery.safeModeActive,
3955
3966
  })
3956
3967
  phase3Recovery.safeModeActive = safeModeVerdict.blocked
@@ -4133,6 +4144,14 @@ export function apply(ctx: Context, config?: Config): void {
4133
4144
  // 自动同步调度器随插件生命周期停止:插件重载/卸载时清理定时器,
4134
4145
  // 避免旧调度器残留导致重复后台同步。
4135
4146
  ctx.effect(() => () => scheduler.stop(), 'config-manager: autosync scheduler')
4147
+ // 退出兜底释放环境锁:关窗时若后台同步正在跑,各入口的 finally 等不到 ⇒ 锁留盘(见 core/env-lock-lifecycle.ts)。
4148
+ // 强杀 / 崩溃 / 断电仍靠下次启动的自动回收兜底。
4149
+ const releaseLockOnExit = createExitLockReleaser(envLockManager)
4150
+ process.once('exit', releaseLockOnExit)
4151
+ ctx.effect(() => () => {
4152
+ process.removeListener('exit', releaseLockOnExit)
4153
+ releaseLockOnExit()
4154
+ }, 'config-manager: environment lock exit release')
4136
4155
  // m-profiles:实例心跳(自报 + 定期刷新);dispose 时撤回自己的心跳文件,别让别人把死实例当成活的。
4137
4156
  ctx.effect(() => {
4138
4157
  const stopHeartbeat = profileRuntime.startHeartbeat()
@@ -5,28 +5,60 @@
5
5
  * path/methods 就是唯一声明处;围栏、方法判定与顶层异常处理由 src/routes/kit.ts 在注册点统一提供。
6
6
  */
7
7
 
8
- import { endpoint, writeJson } from './kit.ts'
8
+ import { endpoint, requireJsonObject, writeJson } from './kit.ts'
9
9
  import type { WebRoute } from './kit.ts'
10
10
  import type { RoutesEnv } from './context.ts'
11
- import { parseHistoryQuery, queryHistory, renderExport, summarizeHistory } from '../core/migration-history.ts'
11
+ import {
12
+ DEFAULT_MIGRATION_RETENTION,
13
+ HISTORY_RETENTION_MAX,
14
+ HISTORY_RETENTION_MIN,
15
+ isValidHistoryRetention,
16
+ parseHistoryQuery,
17
+ queryHistory,
18
+ renderExport,
19
+ resolveHistoryRetention,
20
+ summarizeHistory,
21
+ } from '../core/migration-history.ts'
22
+ import { readUiPrefs, updateUiPrefs } from '../sync/ui-prefs.ts'
23
+
24
+ /** 列表接口的 limit 上限:防「?limit=99999999」把只读端点的读放大成拒绝服务面。 */
25
+ const HISTORY_LIST_LIMIT_MAX = 5000
26
+
27
+ /**
28
+ * 解析列表请求的 limit:缺省 / 非法 / 负数 = 0(= 全量,老口径不变);超上限按上限截断。
29
+ * 只接受十进制整数字面量(parseInt 会把 '12abc' 读成 12,故先用正则判形)。
30
+ */
31
+ function parseListLimit(raw: string | null): number {
32
+ if (raw === null || !/^\d+$/.test(raw.trim())) return 0
33
+ const n = Number.parseInt(raw.trim(), 10)
34
+ if (!Number.isFinite(n) || n <= 0) return 0
35
+ return Math.min(n, HISTORY_LIST_LIMIT_MAX)
36
+ }
12
37
 
13
38
  export function historyRoutes(env: RoutesEnv): WebRoute[] {
14
39
  const {
15
40
  history,
16
41
  host,
42
+ msg,
43
+ syncDir,
44
+ withMutationGate,
17
45
  } = env
18
46
  return [
19
47
  // ------------------------------------------------------------ history
20
48
  // Phase 6:迁移历史审计(统一历史引擎)。只读 GET:列表(过滤)+ 导出。
21
49
  // loopback fence(guard)与全仓一致——仅同源 + loopback 可访问。
50
+ // ?limit=N:只读最近 N 条(文件名尾部窗口)。首页只要最近几十条活动,全量读 + 全量回传
51
+ // 会把首屏骨架拖到秒级(真机 2360 条:纯 IO/解析 650 ms,冷启动含回传 9.7 s)。
52
+ // 响应始终带 total(目录合法文件总数)与 scanned(本次实际读取条数),避免 UI 把窗口当全量。
22
53
  endpoint({ path: '/api/dsh-config-manager/history', methods: ['GET'] }, async (req, res) => {
23
54
  try {
24
55
  const url = new URL(req.url ?? '/', 'http://localhost')
25
56
  const q = parseHistoryQuery(Object.fromEntries(url.searchParams))
26
- const { entries, corrupted } = await history.read()
57
+ const limit = parseListLimit(url.searchParams.get('limit'))
58
+ const { entries, corrupted, total } = await history.read({ limit })
27
59
  const filtered = queryHistory(entries, q)
28
60
  const stats = summarizeHistory(filtered)
29
- writeJson(res, 200, { ok: true, entries: filtered, stats, corrupted })
61
+ writeJson(res, 200, { ok: true, entries: filtered, stats, corrupted, total: total ?? entries.length, scanned: entries.length, limit })
30
62
  } catch (error) {
31
63
  writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
32
64
  }
@@ -52,5 +84,50 @@ export function historyRoutes(env: RoutesEnv): WebRoute[] {
52
84
  writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
53
85
  }
54
86
  }),
87
+ // ------------------------------------------------------ history/retention
88
+ // 迁移历史自动清理(issue:历史目录只增不减,真机已 2360 条 / 0.67 MB)。
89
+ // 策略存 ui-prefs.json 的 historyRetentionMaxEntries(0 = 不限制,缺省 1000);
90
+ // 宿主在每次写入历史后按该值节流清理最旧条目(调度与取舍 → src/core/history-prune.ts)。
91
+ // GET → 当前策略 + 目录现状;POST → 改策略并立即清理一次(同一道写入门)。
92
+ // 一条 exact 路由 + 方法内部分发:webserver 对重复 (kind, path) 直接抛错。
93
+ endpoint({ path: '/api/dsh-config-manager/history/retention', methods: ['GET', 'POST'] }, async (req, res) => {
94
+ if (req.method === 'GET') {
95
+ try {
96
+ const [prefs, total] = await Promise.all([readUiPrefs(syncDir), history.count()])
97
+ writeJson(res, 200, {
98
+ ok: true,
99
+ maxEntries: resolveHistoryRetention(prefs.historyRetentionMaxEntries),
100
+ total,
101
+ defaultMaxEntries: DEFAULT_MIGRATION_RETENTION,
102
+ allowedMin: HISTORY_RETENTION_MIN,
103
+ allowedMax: HISTORY_RETENTION_MAX,
104
+ })
105
+ } catch (error) {
106
+ writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
107
+ }
108
+ return
109
+ }
110
+ // 写分支:删历史属破坏性操作,与其它写路径同一道门(不写审计条目 → 见 history-prune 头注释)。
111
+ await withMutationGate('history-retention', async (gatedReq, gatedRes) => {
112
+ const body = await requireJsonObject(gatedReq)
113
+ const next = body['maxEntries']
114
+ if (!isValidHistoryRetention(next)) {
115
+ writeJson(gatedRes, 400, {
116
+ ok: false,
117
+ code: 'invalid-retention',
118
+ error: msg('route.historyRetentionInvalid', { min: HISTORY_RETENTION_MIN, max: HISTORY_RETENTION_MAX }),
119
+ })
120
+ return
121
+ }
122
+ // 先落策略再清理:清理失败也要让新策略生效(下一次写入会重试),否则用户改完不生效。
123
+ await updateUiPrefs(syncDir, { historyRetentionMaxEntries: next })
124
+ const removed = next > 0 ? await history.retention(next) : []
125
+ const total = await history.count()
126
+ if (removed.length > 0) {
127
+ host.log.info('迁移历史自动清理', { maxEntries: next, removed: removed.length, total })
128
+ }
129
+ writeJson(gatedRes, 200, { ok: true, maxEntries: next, removed: removed.length, total })
130
+ }, { journaled: false })(req, res)
131
+ }),
55
132
  ]
56
133
  }
@@ -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'
package/src/routes/kit.ts CHANGED
@@ -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
  *
@@ -23,6 +23,8 @@ export const zh = {
23
23
  'route.importNoSections': '无分区',
24
24
  'route.importHistorySummary': '导入完成:{sections}(执行 {count} 项)',
25
25
  'route.importIncomplete': '导入未完全成功',
26
+ // ---------- 迁移历史自动清理 ----------
27
+ 'route.historyRetentionInvalid': '保留上限必须是 {min}–{max} 之间的整数(0 = 不限制)',
26
28
  // ---------- 档案 ----------
27
29
  'route.profileLaunchSummary': '启动档案 {name}(独立实例 :{port})',
28
30
  'route.profileCreateSummary': '新建档案 {name}(模板 {template})',
@@ -67,6 +69,7 @@ export const en: Record<keyof typeof zh, string> = {
67
69
  'route.importNoSections': 'no sections',
68
70
  'route.importHistorySummary': 'Import finished: {sections} ({count} item(s) executed)',
69
71
  'route.importIncomplete': 'Import did not fully succeed',
72
+ 'route.historyRetentionInvalid': 'Retention limit must be an integer between {min} and {max} (0 = unlimited)',
70
73
  'route.profileLaunchSummary': 'Launched profile {name} (separate instance :{port})',
71
74
  'route.profileCreateSummary': 'Created profile {name} (template {template})',
72
75
  'route.profileCopySummary': 'Copied profile {from} → {to}{suffix}',
@@ -577,6 +577,9 @@ export class AutoSyncScheduler {
577
577
  let releaseLock: (() => Promise<void>) | null = null;
578
578
  if (this.mutationLock !== undefined) {
579
579
  try {
580
+ // 本轮开始前先自愈:上一轮异常退出留下的**可证** stale 残留锁只会让每轮静默 skip,
581
+ // 用户不重启就永远不同步。只删可证的(owner 确证死亡 / PID 复用),其余保持下面既有的 warn 路径。
582
+ try { await this.mutationLock.reclaimProvableStaleLock?.() } catch { /* 预检失败不改变既有路径 */ }
580
583
  const lk = await withMutationLock(this.mutationLock, { op: 'autosync', target: channel, isBlocked: this.isBlocked });
581
584
  if (lk.context === null) {
582
585
  this.running = false;
@@ -261,6 +261,9 @@ export class BackupScheduler {
261
261
  }
262
262
 
263
263
  try {
264
+ // 本轮开始前先自愈:可证的 stale 残留锁会让每轮备份直接 skipped,用户不重启就永远不备份。
265
+ // 只删可证的(owner 确证死亡 / PID 复用);不可证的仍走下面 runWithMutationLock 的 skipped 分支。
266
+ try { await this.mutationLock?.reclaimProvableStaleLock?.() } catch { /* 预检失败不改变既有路径 */ }
264
267
  // Phase 2 锁:定时备份写入 exports 属 GLOBAL mutation(与 Sync push / 手动备份互斥)。
265
268
  // 无锁环境(测试)→ 不锁定直接执行;锁被占用 → 返回 failed(destructive 不执行)。
266
269
  const result: BackupRunResult = await runWithMutationLock(this.mutationLock, { op: 'backup-schedule', target: 'exports', isBlocked: this.isBlocked }, async (lockCtx) => {
@@ -7,6 +7,10 @@
7
7
  * `getResourceV4`、`oss/auth.go` 的 `getSubResource` / `getSignedStrV4`)**独立重写**一遍,
8
8
  * 只吃「收到的 HTTP 请求」(method / url / 头 / body),绝不复用客户端的签名中间量。
9
9
  *
10
+ * 也照真服务端实现**条件写能力**:PutObject 收到 If-Match / If-None-Match 一律拒(0017-00000245),
11
+ * 只接受 `x-oss-forbid-overwrite: true`(已存在 → 409 FileAlreadyExists)—— 这一层不照真服务端写,
12
+ * 「本地全绿、真机 400」的盲点就会回来(issue #109 第二层)。
13
+ *
10
14
  * 用法:`s3-transport.oss4-server.test.ts`(内存对象存储,逐请求验签)与
11
15
  * `scripts/oss-live-check.mjs`(真桶联调)。它证明的是「与本仓库对官方算法的独立复现一致」,
12
16
  * 不等于官方服务端盖章 —— 真桶连通性要靠带真实密钥跑一次脚本。
@@ -134,6 +138,11 @@ export function verifyOssV4(
134
138
  return { ok: true, reason: '', canonicalRequest, stringToSign, signature, objectKey, bucketLevel };
135
139
  }
136
140
 
141
+ /** 真 OSS 会拒绝的条件写头(PutObject 不支持;错误码 0017-00000245)。 */
142
+ const IF_CONDITIONAL_HEADERS = ['if-match', 'if-none-match'] as const;
143
+ /** OSS 回显头名时用的原始大小写(真机报文里看到的是 `If-None-Match`)。 */
144
+ const IF_HEADER_ECHO: Record<string, string> = { 'if-match': 'If-Match', 'if-none-match': 'If-None-Match' };
145
+
137
146
  interface StoredObject {
138
147
  body: string;
139
148
  etag: string;
@@ -174,13 +183,20 @@ export function makeOssVerifyServer(cfg: Oss4VerifyConfig): {
174
183
  const h = lower(headers);
175
184
  const existing = objects.get(key);
176
185
  if (method === 'PUT') {
177
- const ifMatch = h['if-match'];
178
- const ifNoneMatch = h['if-none-match'];
179
- if (ifMatch !== undefined && existing !== undefined && ifMatch.replace(/"/g, '') !== existing.etag) {
180
- return respond(412, '<Error><Code>PreconditionFailed</Code></Error>');
186
+ // 真 OSS 的 PutObject **不支持 If-Match / If-None-Match**:收到就回
187
+ // 400 InvalidArgument「A header you provided implies functionality that is not implemented.」
188
+ // (错误码 0017-00000245,issue #109 第二层)。这里必须照真服务端拒掉 —— 之前这个验签器
189
+ // 自己实现了 if-none-match,等于用自家规则验自家人,于是「14 个请求零失败」漏掉了这一层。
190
+ const unsupported = IF_CONDITIONAL_HEADERS.find((n) => h[n] !== undefined);
191
+ if (unsupported !== undefined) {
192
+ return respond(400, '<Error><Code>InvalidArgument</Code><Message>A header you provided implies '
193
+ + 'functionality that is not implemented.</Message><Header>' + IF_HEADER_ECHO[unsupported]
194
+ + '</Header><EC>0017-00000245</EC></Error>');
181
195
  }
182
- if (ifNoneMatch === '*' && existing !== undefined) {
183
- return respond(412, '<Error><Code>PreconditionFailed</Code></Error>');
196
+ // OSS 唯一支持的「禁止覆盖」:对象已存在即 409 FileAlreadyExists。
197
+ if ((h['x-oss-forbid-overwrite'] ?? '').trim().toLowerCase() === 'true' && existing !== undefined) {
198
+ return respond(409, '<Error><Code>FileAlreadyExists</Code><Message>The object you specified already '
199
+ + 'exists and cannot be overwritten again.</Message></Error>');
184
200
  }
185
201
  const body = opts.body ?? '';
186
202
  const etag = sha256(body).slice(0, 32);