dsh-config-manager 0.3.1 → 0.4.1
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.
- package/lib/client.d.ts +54 -3
- package/lib/client.js +1078 -845
- package/lib/core/env-lock-lifecycle.d.ts +45 -0
- package/lib/core/env-lock-lifecycle.js +43 -0
- package/lib/core/history-prune.d.ts +34 -0
- package/lib/core/history-prune.js +43 -0
- package/lib/core/index.d.ts +1 -1
- package/lib/core/index.js +1 -1
- package/lib/core/messages-core.d.ts +1 -0
- package/lib/core/messages-core.js +2 -0
- package/lib/core/migration-history.d.ts +46 -4
- package/lib/core/migration-history.js +60 -7
- package/lib/index.d.ts +2 -2
- package/lib/index.js +26 -8
- package/lib/routes/history.js +70 -5
- package/lib/routes/index.d.ts +1 -1
- package/lib/routes/kit.d.ts +2 -2
- package/lib/routes/messages.d.ts +1 -0
- package/lib/routes/messages.js +3 -0
- package/lib/sync/autosync-scheduler.js +12 -2
- package/lib/sync/backup-scheduler.js +6 -0
- package/lib/sync/baseline-heal.d.ts +35 -0
- package/lib/sync/baseline-heal.js +39 -0
- package/lib/sync/push-precheck.d.ts +35 -0
- package/lib/sync/push-precheck.js +58 -0
- package/lib/sync/sync-engine.d.ts +9 -12
- package/lib/sync/sync-engine.js +24 -43
- package/lib/sync/ui-prefs.d.ts +8 -0
- package/lib/sync/ui-prefs.js +8 -0
- package/lib/ui/history-model.js +3 -2
- package/lib/ui/overview-view.d.ts +3 -3
- package/lib/ui/overview-view.js +9 -1
- package/lib/utils/env-lock.d.ts +55 -1
- package/lib/utils/env-lock.js +131 -2
- package/lib/utils/messages-utils.d.ts +3 -0
- package/lib/utils/messages-utils.js +6 -0
- package/package.json +1 -1
- package/src/client/common/InfoHint.tsx +12 -3
- package/src/client/common/Skeleton.tsx +45 -8
- package/src/client/common/info-hint-guard.test.ts +196 -0
- package/src/client/common/routes.ts +3 -1
- package/src/client/common/skeleton-guard.test.ts +58 -0
- package/src/client/common/ui.tsx +17 -4
- package/src/client/config-manager.module.css +256 -27
- package/src/client/css-motion-guard.test.ts +230 -0
- package/src/client/environment/EnvironmentPanel.tsx +41 -29
- package/src/client/environment/maintenance/DiskUsageCard.tsx +28 -33
- package/src/client/environment/profiles-incomplete-ui.test.ts +9 -5
- package/src/client/export/ExportView.tsx +6 -6
- package/src/client/history/HistoryPanel.tsx +87 -2
- package/src/client/history/history-api.ts +49 -3
- package/src/client/history/history-locales.ts +32 -0
- package/src/client/home/HomePanel.tsx +64 -26
- package/src/client/locales.ts +2 -0
- package/src/client/market/MyConfigsWizard.tsx +12 -3
- package/src/client/recovery/RecoveryPanel.tsx +93 -92
- package/src/client/recovery/RollbackCard.tsx +25 -16
- package/src/client/sync/AutosyncCard.tsx +12 -6
- package/src/client/sync/ChannelConfigDialog.tsx +45 -45
- package/src/client/sync/DecryptPasswordCard.tsx +3 -3
- package/src/client/sync/SecurityOptionsCard.tsx +3 -3
- package/src/client/sync/SyncSectionPickerDialog.tsx +3 -3
- package/src/client/sync/history-model.ts +3 -0
- package/src/client/sync/sync-locales.ts +2 -0
- package/src/core/env-lock-lifecycle.ts +73 -0
- package/src/core/history-prune.test.ts +115 -0
- package/src/core/history-prune.ts +61 -0
- package/src/core/index.ts +2 -0
- package/src/core/messages-core.ts +2 -0
- package/src/core/migration-history.test.ts +97 -0
- package/src/core/migration-history.ts +74 -9
- package/src/index.ts +27 -8
- package/src/routes/history.ts +81 -4
- package/src/routes/index.ts +1 -1
- package/src/routes/kit.ts +2 -2
- package/src/routes/messages.ts +3 -0
- package/src/sync/autosync-scheduler.test.ts +23 -0
- package/src/sync/autosync-scheduler.ts +9 -2
- package/src/sync/backup-scheduler.ts +3 -0
- package/src/sync/baseline-heal.ts +74 -0
- package/src/sync/push-precheck.ts +75 -0
- package/src/sync/sync-engine.test.ts +88 -0
- package/src/sync/sync-engine.ts +33 -43
- package/src/sync/ui-prefs.test.ts +32 -0
- package/src/sync/ui-prefs.ts +16 -0
- package/src/ui/history-model.test.ts +2 -1
- package/src/ui/history-model.ts +3 -2
- package/src/ui/overview-view.test.ts +12 -0
- package/src/ui/overview-view.ts +12 -4
- package/src/utils/env-lock.test.ts +107 -0
- package/src/utils/env-lock.ts +124 -2
- package/src/utils/messages-utils.ts +6 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { test } from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { createHistoryPruner } from './history-prune.ts'
|
|
4
|
+
|
|
5
|
+
/** 记录调用的假 store:默认删除「多余」条目,返回被删数量。 */
|
|
6
|
+
function fakeHistory(behaviour: 'ok' | 'throw' = 'ok') {
|
|
7
|
+
const calls: number[] = []
|
|
8
|
+
return {
|
|
9
|
+
calls,
|
|
10
|
+
async retention(limit: number): Promise<string[]> {
|
|
11
|
+
calls.push(limit)
|
|
12
|
+
if (behaviour === 'throw') throw new Error('EACCES')
|
|
13
|
+
return ['a.json', 'b.json'].slice(0, Math.max(0, limit - 1))
|
|
14
|
+
},
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function fakeLog() {
|
|
19
|
+
const info: Array<{ message: string; meta?: Record<string, unknown> }> = []
|
|
20
|
+
const warn: Array<{ message: string; meta?: Record<string, unknown> }> = []
|
|
21
|
+
return {
|
|
22
|
+
info,
|
|
23
|
+
warn,
|
|
24
|
+
logger: {
|
|
25
|
+
info: (message: string, meta?: Record<string, unknown>) => { info.push({ message, ...(meta ? { meta } : {}) }) },
|
|
26
|
+
warn: (message: string, meta?: Record<string, unknown>) => { warn.push({ message, ...(meta ? { meta } : {}) }) },
|
|
27
|
+
},
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
test('启动触发:按配置上限清理一次并写日志;0 = 不限制时一次都不删', async () => {
|
|
32
|
+
const history = fakeHistory()
|
|
33
|
+
const { logger, info } = fakeLog()
|
|
34
|
+
const prune = createHistoryPruner({ history, log: logger, readRetentionLimit: async () => 3 })
|
|
35
|
+
await prune('startup')
|
|
36
|
+
assert.deepEqual(history.calls, [3], '启动应清一次,且用配置值')
|
|
37
|
+
assert.equal(info.length, 1, '删掉了条目就要留一条日志')
|
|
38
|
+
assert.equal(info[0]?.message, '迁移历史自动清理')
|
|
39
|
+
assert.deepEqual(info[0]?.meta, { maxEntries: 3, removed: 2 })
|
|
40
|
+
|
|
41
|
+
const unlimited = fakeHistory()
|
|
42
|
+
const second = fakeLog()
|
|
43
|
+
const pruneUnlimited = createHistoryPruner({ history: unlimited, log: second.logger, readRetentionLimit: async () => 0 })
|
|
44
|
+
await pruneUnlimited('startup')
|
|
45
|
+
assert.deepEqual(unlimited.calls, [], '0 = 不限制 ⇒ 绝不批量删')
|
|
46
|
+
assert.equal(second.info.length, 0)
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
test('非法配置回落缺省 1000(不因手改 ui-prefs 把历史全删)', async () => {
|
|
50
|
+
const history = fakeHistory()
|
|
51
|
+
const { logger } = fakeLog()
|
|
52
|
+
const prune = createHistoryPruner({ history, log: logger, readRetentionLimit: async () => '1000' })
|
|
53
|
+
await prune('startup')
|
|
54
|
+
assert.deepEqual(history.calls, [1000], '字符串等非法值必须回落 DEFAULT_MIGRATION_RETENTION')
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
test('写入触发按 60 s 节流:紧接着的第二次 append 跳过,窗口过后再放行', async () => {
|
|
58
|
+
const history = fakeHistory()
|
|
59
|
+
const { logger } = fakeLog()
|
|
60
|
+
let clock = 1_000_000
|
|
61
|
+
const prune = createHistoryPruner({ history, log: logger, readRetentionLimit: async () => 5, now: () => clock })
|
|
62
|
+
await prune('startup')
|
|
63
|
+
await prune('append')
|
|
64
|
+
assert.deepEqual(history.calls, [5], '刚启动清理过 ⇒ 紧随的 append 落在节流窗口内');
|
|
65
|
+
clock += 61_000
|
|
66
|
+
await prune('append')
|
|
67
|
+
assert.deepEqual(history.calls, [5, 5], '窗口过后 append 应执行')
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
test('防重入:并发调用只有一次真正执行', async () => {
|
|
71
|
+
const calls: number[] = []
|
|
72
|
+
let release!: () => void
|
|
73
|
+
const gate = new Promise<void>((resolve) => { release = resolve })
|
|
74
|
+
const history = {
|
|
75
|
+
calls,
|
|
76
|
+
async retention(limit: number): Promise<string[]> {
|
|
77
|
+
calls.push(limit)
|
|
78
|
+
await gate
|
|
79
|
+
return []
|
|
80
|
+
},
|
|
81
|
+
}
|
|
82
|
+
const prune = createHistoryPruner({ history, log: fakeLog().logger, readRetentionLimit: async () => 2, now: () => 0 })
|
|
83
|
+
const first = prune('startup')
|
|
84
|
+
const second = prune('append')
|
|
85
|
+
await second
|
|
86
|
+
assert.deepEqual(calls, [2], '在飞期间不得并发再删一遍')
|
|
87
|
+
release()
|
|
88
|
+
await first
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
test('失败只进日志、绝不抛错(清理失败不能拖垮历史写入)', async () => {
|
|
92
|
+
const history = fakeHistory('throw')
|
|
93
|
+
const { logger, warn, info } = fakeLog()
|
|
94
|
+
const prune = createHistoryPruner({ history, log: logger, readRetentionLimit: async () => 10 })
|
|
95
|
+
await prune('startup')
|
|
96
|
+
assert.equal(info.length, 0)
|
|
97
|
+
assert.equal(warn.length, 1)
|
|
98
|
+
assert.equal(warn[0]?.message, '迁移历史自动清理失败')
|
|
99
|
+
assert.match(String(warn[0]?.meta?.['error']), /EACCES/)
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
test('读配置本身失败也走 warn 分支(ui-prefs 读不出不阻塞后续触发)', async () => {
|
|
103
|
+
const history = fakeHistory()
|
|
104
|
+
const { logger, warn } = fakeLog()
|
|
105
|
+
let attempts = 0
|
|
106
|
+
const prune = createHistoryPruner({
|
|
107
|
+
history,
|
|
108
|
+
log: logger,
|
|
109
|
+
readRetentionLimit: async () => { attempts += 1; if (attempts === 1) throw new Error('boom'); return 4 },
|
|
110
|
+
})
|
|
111
|
+
await prune('startup')
|
|
112
|
+
assert.equal(warn.length, 1)
|
|
113
|
+
await prune('startup')
|
|
114
|
+
assert.deepEqual(history.calls, [4], '下一次触发应恢复正常(inFlight 已复位)')
|
|
115
|
+
})
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 迁移历史自动清理的调度器(宿主只做接线,逻辑留在这里)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独成文件:src/index.ts 有体量棘轮(tests/file-size-ratchet.test.ts),
|
|
5
|
+
* 而这段调度与 HTTP 路由无关 —— 只依赖「历史 store + ui-prefs 策略 + 日志」三件事。
|
|
6
|
+
*
|
|
7
|
+
* 语义:保留上限 = ui-prefs.json 的 historyRetentionMaxEntries(缺省 1000;0 = 不限制,绝不批量删)。
|
|
8
|
+
* 触发:启动后一次 + 每次历史写入成功后(写入触发按 intervalMs 节流;同时只跑一个)。
|
|
9
|
+
* **不写审计条目**:清理本身若进历史,则「保留最近 N 条」永远差一条,每次写入都会再删再写
|
|
10
|
+
* (自反馈 churn);因此清理只删最旧文件,结果只进宿主日志。
|
|
11
|
+
*/
|
|
12
|
+
import { resolveHistoryRetention, type MigrationStore } from './migration-history.ts'
|
|
13
|
+
|
|
14
|
+
/** 只用到 retention;收窄依赖便于单测替身。 */
|
|
15
|
+
export type HistoryPruneStore = Pick<MigrationStore, 'retention'>
|
|
16
|
+
|
|
17
|
+
export interface HistoryPruneLogger {
|
|
18
|
+
info(message: string, meta?: Record<string, unknown>): void
|
|
19
|
+
warn(message: string, meta?: Record<string, unknown>): void
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface HistoryPrunerOptions {
|
|
23
|
+
history: HistoryPruneStore
|
|
24
|
+
/**
|
|
25
|
+
* 读取用户配置的保留上限(原值,非法由 resolveHistoryRetention 归一)。
|
|
26
|
+
* 由宿主注入:core 层不得 import ../sync/*(tests/architecture-boundaries.test.ts)。
|
|
27
|
+
*/
|
|
28
|
+
readRetentionLimit: () => Promise<unknown>
|
|
29
|
+
log: HistoryPruneLogger
|
|
30
|
+
/** 写入触发的节流窗口(缺省 60 s);启动触发不受它影响。 */
|
|
31
|
+
intervalMs?: number
|
|
32
|
+
/** 注入时钟(测试用)。 */
|
|
33
|
+
now?: () => number
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type HistoryPruneTrigger = 'startup' | 'append'
|
|
37
|
+
|
|
38
|
+
/** 返回 pruneHistory(trigger):fire-and-forget 调用,永不抛错(失败只进日志)。 */
|
|
39
|
+
export function createHistoryPruner(options: HistoryPrunerOptions): (trigger: HistoryPruneTrigger) => Promise<void> {
|
|
40
|
+
const { history, readRetentionLimit, log, intervalMs = 60_000, now = Date.now } = options
|
|
41
|
+
let inFlight = false
|
|
42
|
+
let lastAt = 0
|
|
43
|
+
return async function pruneHistory(trigger: HistoryPruneTrigger): Promise<void> {
|
|
44
|
+
if (inFlight) return
|
|
45
|
+
const at = now()
|
|
46
|
+
// 节流只压「写入触发」:lastAt 由上一次实际执行决定,启动那一次基本总是放行。
|
|
47
|
+
if (trigger === 'append' && at - lastAt < intervalMs) return
|
|
48
|
+
inFlight = true
|
|
49
|
+
lastAt = at
|
|
50
|
+
try {
|
|
51
|
+
const limit = resolveHistoryRetention(await readRetentionLimit())
|
|
52
|
+
if (limit <= 0) return
|
|
53
|
+
const removed = await history.retention(limit)
|
|
54
|
+
if (removed.length > 0) log.info('迁移历史自动清理', { maxEntries: limit, removed: removed.length })
|
|
55
|
+
} catch (error) {
|
|
56
|
+
log.warn('迁移历史自动清理失败', { error: error instanceof Error ? error.message : String(error) })
|
|
57
|
+
} finally {
|
|
58
|
+
inFlight = false
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
package/src/core/index.ts
CHANGED
|
@@ -52,6 +52,8 @@ export {
|
|
|
52
52
|
parseHistoryQuery, isValidMigrationKind, redactHistoryText,
|
|
53
53
|
makeHistoryFilename, isHistoryBasename, MIGRATION_HISTORY_DIR,
|
|
54
54
|
DEFAULT_MIGRATION_RETENTION, MIGRATION_HISTORY_SCHEMA_VERSION,
|
|
55
|
+
HISTORY_RETENTION_MIN, HISTORY_RETENTION_MAX,
|
|
56
|
+
isValidHistoryRetention, resolveHistoryRetention,
|
|
55
57
|
type MigrationKind, type MigrationResult, type MigrationHistoryEntry,
|
|
56
58
|
type StoredMigrationHistoryEntry, type MigrationQuery, type MigrationHistoryStats,
|
|
57
59
|
type ExportFormat, type ReadMigrationResult, type AppendResult, type MigrationIo,
|
|
@@ -91,6 +91,7 @@ export const zh = {
|
|
|
91
91
|
'core.migrationHistory.resultSuccess': '成功',
|
|
92
92
|
'core.migrationHistory.resultFailed': '失败',
|
|
93
93
|
'core.migrationHistory.resultSkipped': '跳过',
|
|
94
|
+
'core.migrationHistory.resultPending': '待裁决',
|
|
94
95
|
|
|
95
96
|
// ---------- local-plugin-pack ----------
|
|
96
97
|
'core.localPluginPack.dirCreateFailed': '本地插件打包目录创建失败,已跳过全部本地插件: {reason}',
|
|
@@ -405,6 +406,7 @@ export const en: Record<keyof typeof zh, string> = {
|
|
|
405
406
|
'core.migrationHistory.resultSuccess': 'success',
|
|
406
407
|
'core.migrationHistory.resultFailed': 'failed',
|
|
407
408
|
'core.migrationHistory.resultSkipped': 'skipped',
|
|
409
|
+
'core.migrationHistory.resultPending': 'needs decision',
|
|
408
410
|
|
|
409
411
|
// ---------- local-plugin-pack ----------
|
|
410
412
|
'core.localPluginPack.dirCreateFailed': 'Failed to create the local plugin packing directory; skipped all local plugins: {reason}',
|
|
@@ -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, []);
|
|
@@ -256,6 +334,25 @@ test('QUERYABLE:parseHistoryQuery 解析过滤参数并丢弃非法 kind', ()
|
|
|
256
334
|
assert.deepEqual(q.sections, ['plugins']);
|
|
257
335
|
});
|
|
258
336
|
|
|
337
|
+
test('0.4.1 待裁决:result=pending 可落盘读回、可被查询过滤、导出写人话而非裸枚举', async (t) => {
|
|
338
|
+
const dir = tmp(t);
|
|
339
|
+
const appended = await mkStore(dir).append(makeRaw({ kind: 'autosync', result: 'pending', summary: '自动同步有 1 个分区待裁决' }));
|
|
340
|
+
assert.equal(appended.ok, true);
|
|
341
|
+
|
|
342
|
+
const read = await mkStore(dir).read();
|
|
343
|
+
assert.deepEqual(read.corrupted, [], 'pending 是合法结果 —— 不得被当成篡改条目静默丢弃');
|
|
344
|
+
assert.equal(read.entries.length, 1);
|
|
345
|
+
assert.equal(read.entries[0]!.result, 'pending', '读回必须保留 pending(否则「待裁决」在刷新后消失)');
|
|
346
|
+
|
|
347
|
+
assert.deepEqual(parseHistoryQuery({ result: 'pending,failed' }).result, ['pending', 'failed'], '过滤白名单必须认 pending');
|
|
348
|
+
assert.equal(queryHistory(read.entries, { result: ['pending'] }).length, 1);
|
|
349
|
+
assert.equal(queryHistory(read.entries, { result: ['failed'] }).length, 0, 'pending 不得被当成 failed 命中');
|
|
350
|
+
|
|
351
|
+
const md = renderExport(read.entries, 'markdown', 'zh');
|
|
352
|
+
assert.match(md, /待裁决/, '导出要写人话');
|
|
353
|
+
assert.ok(!md.includes('| pending |'), '原文列绝不出现裸枚举值');
|
|
354
|
+
});
|
|
355
|
+
|
|
259
356
|
test('EXPORTABLE:renderExport json 输出合法 JSON + 统计', () => {
|
|
260
357
|
const entries = [sanitizeEntry(makeRaw()), sanitizeEntry(makeRaw({ kind: 'restore', result: 'failed' }))];
|
|
261
358
|
const json = renderExport(entries, 'json');
|
|
@@ -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.';
|
|
@@ -56,8 +79,29 @@ const MIGRATION_KINDS = [
|
|
|
56
79
|
/** §5 覆盖的操作 kind(COMPLETE 不变量;常量枚举,天然非敏感)。 */
|
|
57
80
|
export type MigrationKind = (typeof MIGRATION_KINDS)[number];
|
|
58
81
|
|
|
59
|
-
/**
|
|
60
|
-
|
|
82
|
+
/**
|
|
83
|
+
* 操作结果。
|
|
84
|
+
*
|
|
85
|
+
* 'pending'(0.4.1):操作**跑完了但仍有待裁决项**(自动同步上传成功、下行冲突未裁决;
|
|
86
|
+
* 合并已应用一部分)。它不是 failed —— 网络/凭据/repo 都是好的;也不是 skipped ——
|
|
87
|
+
* 那一轮确实做了事。旧实现把 partial 直接折成 'failed',用户看到「自动同步 失败」而
|
|
88
|
+
* 实际只需要在同步页确认一次冲突。读侧(parseEntry / query 解析)必须接受该值,
|
|
89
|
+
* 否则含 pending 的历史条目会被整条丢弃。
|
|
90
|
+
*/
|
|
91
|
+
export type MigrationResult = 'success' | 'failed' | 'skipped' | 'pending';
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* 自动同步一轮的状态 → 历史 result(宿主 appendHistoryFn 的唯一映射,0.4.1)。
|
|
95
|
+
*
|
|
96
|
+
* 关键一条:`partial`(跑完了但仍有待裁决分区)**不是** failed —— 通道与凭据都正常,
|
|
97
|
+
* 只是需要用户在同步页确认一次冲突。落成 failed 会让首页红字报「同步失败」,
|
|
98
|
+
* 用户据此去查网络/凭据,方向完全错。
|
|
99
|
+
*/
|
|
100
|
+
export function historyResultFromAutosyncStatus(status: 'success' | 'skipped' | 'partial' | 'failed'): MigrationResult {
|
|
101
|
+
if (status === 'success') return 'success';
|
|
102
|
+
if (status === 'skipped') return 'skipped';
|
|
103
|
+
return status === 'partial' ? 'pending' : 'failed';
|
|
104
|
+
}
|
|
61
105
|
|
|
62
106
|
/** 触发来源(常量)。 */
|
|
63
107
|
export type MigrationSource = 'api' | 'autosync' | 'backup-scheduler' | 'recovery' | 'cli' | 'internal';
|
|
@@ -120,6 +164,8 @@ export interface ReadMigrationResult {
|
|
|
120
164
|
entries: StoredMigrationHistoryEntry[];
|
|
121
165
|
/** 被跳过/损坏的文件名(读取时识别,UI 可选警示;不静默接受)。 */
|
|
122
166
|
corrupted: string[];
|
|
167
|
+
/** 目录内**合法历史文件**总数(含被 limit 窗口挡在外的旧条目;未统计时为 undefined)。 */
|
|
168
|
+
total?: number;
|
|
123
169
|
}
|
|
124
170
|
|
|
125
171
|
/** 追加写入结果(best-effort 调用方据此判断降级)。 */
|
|
@@ -283,7 +329,7 @@ function parseEntry(text: string): StoredMigrationHistoryEntry | null {
|
|
|
283
329
|
if (p.schemaVersion !== MIGRATION_HISTORY_SCHEMA_VERSION) return null;
|
|
284
330
|
if (!isValidMigrationKind(p.kind)) return null;
|
|
285
331
|
if (typeof p.at !== 'string' || p.at === '') return null;
|
|
286
|
-
if (!['success', 'failed', 'skipped'].includes(p.result)) return null;
|
|
332
|
+
if (!['success', 'failed', 'skipped', 'pending'].includes(p.result)) return null;
|
|
287
333
|
if (typeof p.source !== 'string') return null;
|
|
288
334
|
if (typeof p.summary !== 'string') return null;
|
|
289
335
|
// 可选字段校验
|
|
@@ -348,13 +394,22 @@ export class MigrationStore {
|
|
|
348
394
|
}
|
|
349
395
|
}
|
|
350
396
|
|
|
351
|
-
/**
|
|
352
|
-
|
|
397
|
+
/**
|
|
398
|
+
* 读取合法历史条目(旧→新;损坏/非史文件跳过并计数)。
|
|
399
|
+
*
|
|
400
|
+
* limit>0 时只读**最近 limit 条**(按文件名排序的尾部窗口)——首屏只要最近几十条活动,
|
|
401
|
+
* 整目录 readFile+parse 是历史目录唯一的慢点(真机 2360 条 ≈ 650 ms 纯 IO/解析,
|
|
402
|
+
* 叠上全量 JSON 回传即首页骨架 ~9.7 s 冷启动)。total 恒为目录内合法文件总数,
|
|
403
|
+
* 调用方据此区分「共 N 条,本页只含最近 M 条」。
|
|
404
|
+
*/
|
|
405
|
+
async read(opts: { limit?: number } = {}): Promise<ReadMigrationResult> {
|
|
353
406
|
const names = await this.io.readdirNames(this.dir).catch(() => []);
|
|
354
407
|
const entries: StoredMigrationHistoryEntry[] = [];
|
|
355
408
|
const corrupted: string[] = [];
|
|
356
409
|
const sorted = names.filter(isHistoryBasename).sort();
|
|
357
|
-
|
|
410
|
+
const limit = opts.limit !== undefined && Number.isInteger(opts.limit) ? opts.limit : 0;
|
|
411
|
+
const window = limit > 0 && sorted.length > limit ? sorted.slice(sorted.length - limit) : sorted;
|
|
412
|
+
for (const name of window) {
|
|
358
413
|
const p = path.join(this.dir, name);
|
|
359
414
|
let text: string;
|
|
360
415
|
try {
|
|
@@ -368,7 +423,13 @@ export class MigrationStore {
|
|
|
368
423
|
if (parsed === null) { corrupted.push(name); continue; }
|
|
369
424
|
entries.push(parsed);
|
|
370
425
|
}
|
|
371
|
-
return { entries, corrupted };
|
|
426
|
+
return { entries, corrupted, total: sorted.length };
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** 目录内合法历史文件总数(只 readdir,不读文件内容;供「自动清理」行展示)。 */
|
|
430
|
+
async count(): Promise<number> {
|
|
431
|
+
const names = await this.io.readdirNames(this.dir).catch(() => []);
|
|
432
|
+
return names.filter(isHistoryBasename).length;
|
|
372
433
|
}
|
|
373
434
|
|
|
374
435
|
/**
|
|
@@ -378,6 +439,8 @@ export class MigrationStore {
|
|
|
378
439
|
async retention(limit = DEFAULT_MIGRATION_RETENTION): Promise<string[]> {
|
|
379
440
|
const names = (await this.io.readdirNames(this.dir).catch(() => [])).filter(isHistoryBasename).sort();
|
|
380
441
|
const removed: string[] = [];
|
|
442
|
+
// 0(或负数)= 不限制:调用方显式关闭自动清理时按「保留全部」处理,绝不当作「删光」。
|
|
443
|
+
if (!Number.isFinite(limit) || limit <= 0) return removed;
|
|
381
444
|
if (names.length <= limit) return removed;
|
|
382
445
|
const toRemove = names.slice(0, names.length - limit);
|
|
383
446
|
for (const name of toRemove) {
|
|
@@ -437,7 +500,9 @@ export function renderExport(entries: StoredMigrationHistoryEntry[], format: Exp
|
|
|
437
500
|
? T('core.migrationHistory.resultSuccess')
|
|
438
501
|
: r === 'failed'
|
|
439
502
|
? T('core.migrationHistory.resultFailed')
|
|
440
|
-
:
|
|
503
|
+
: r === 'pending'
|
|
504
|
+
? T('core.migrationHistory.resultPending')
|
|
505
|
+
: T('core.migrationHistory.resultSkipped');
|
|
441
506
|
|
|
442
507
|
if (format === 'json') {
|
|
443
508
|
const stats = summarizeHistory(entries);
|
|
@@ -464,7 +529,7 @@ export function parseHistoryQuery(raw: Record<string, unknown>): MigrationQuery
|
|
|
464
529
|
const kinds = parseList(raw['kind']);
|
|
465
530
|
if (kinds.length > 0) q.kinds = kinds.filter(isValidMigrationKind);
|
|
466
531
|
const results = parseList(raw['result']);
|
|
467
|
-
if (results.length > 0) q.result = results.filter((r): r is MigrationResult => r === 'success' || r === 'failed' || r === 'skipped');
|
|
532
|
+
if (results.length > 0) q.result = results.filter((r): r is MigrationResult => r === 'success' || r === 'failed' || r === 'skipped' || r === 'pending');
|
|
468
533
|
const sections = parseList(raw['sections']);
|
|
469
534
|
if (sections.length > 0) q.sections = sections;
|
|
470
535
|
const from = parseNum(raw['from']);
|
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,14 +125,15 @@ 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'
|
|
131
132
|
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
|
-
import { MigrationStore, type MigrationKind, type MigrationResult, MIGRATION_HISTORY_DIR } from './core/migration-history.ts'
|
|
135
|
+
import { MigrationStore, type MigrationKind, type MigrationResult, historyResultFromAutosyncStatus, 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.
|
|
186
|
+
export const PLUGIN_VERSION = '0.4.1'
|
|
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
|
-
* 其余
|
|
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) })
|
|
@@ -2999,7 +3007,7 @@ function makeRoutes(deps: RoutesDeps): { routes: WebRoute[]; scheduler: AutoSync
|
|
|
2999
3007
|
await appendAutosyncEntry(syncDir, entry).catch(() => undefined)
|
|
3000
3008
|
await history.append({
|
|
3001
3009
|
kind: 'autosync',
|
|
3002
|
-
result: entry.status
|
|
3010
|
+
result: historyResultFromAutosyncStatus(entry.status),
|
|
3003
3011
|
sections: entry.appliedSections ?? [],
|
|
3004
3012
|
source: 'autosync',
|
|
3005
3013
|
summary: engineMsg('host.autosyncSummary', {
|
|
@@ -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
|
-
* 其余
|
|
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
|
|
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:
|
|
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()
|